printf question

J

John Black

Hopefully a simple question...

Given this printf that specifies some fixed length left justified columns:

printf "%-30s, %-30s, %-30s\n", $a, $b, $c;

How can I make the hardcoded number 30 use a variable, say $len instead?

This does not work:

printf "%-$lens, %-$lens, %-lens\n", $a, $b, $c;

I'm guessing because perl would have trouble knowing that the s at the end is not part of the
variable? Thanks.

John Black
 
P

Peter J. Holzer

Hopefully a simple question...

Given this printf that specifies some fixed length left justified columns:

printf "%-30s, %-30s, %-30s\n", $a, $b, $c;

How can I make the hardcoded number 30 use a variable, say $len instead?

This does not work:

printf "%-$lens, %-$lens, %-lens\n", $a, $b, $c;

I'm guessing because perl would have trouble knowing that the s at the
end is not part of the variable?

Yes.

Either:

printf "%-${len}s, %-${len}s, %-${len}s\n", $a, $b, $c;

Or (more C-like):

printf "%-*s, %-*s, %-*s\n", $len, $a, $len, $b, $len, $c;

hp
 
H

hymie!

In our last episode, the evil Dr. Lacto had captured our hero,
Hopefully a simple question...

Given this printf that specifies some fixed length left justified columns:

printf "%-30s, %-30s, %-30s\n", $a, $b, $c;

How can I make the hardcoded number 30 use a variable, say $len instead?

$format = "%-${len}s, %-${len}s, %-${len}s\n";
printf $format, $a, $b, $c;

--hymie! http://lactose.homelinux.net/~hymie (e-mail address removed)
-------------------------------------------------------------------------------
 
J

John Black

Yes.

Either:

printf "%-${len}s, %-${len}s, %-${len}s\n", $a, $b, $c;

Or (more C-like):

printf "%-*s, %-*s, %-*s\n", $len, $a, $len, $b, $len, $c;

hp

Thanks much. I guess with Perl, its probably going to be adding either {}, [] or ().

John Black
 
J

John Black

In our last episode, the evil Dr. Lacto had captured our hero,


$format = "%-${len}s, %-${len}s, %-${len}s\n";
printf $format, $a, $b, $c;

I like the idea of putting $format in its own variable for readability and for use in
multiple printf statements. Thanks.

John Black
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top