Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

printf syntax

by nate_ (Initiate)
on Aug 13, 2009 at 17:46 UTC ( #788396=perlquestion: print w/replies, xml ) Need Help??
nate_ has asked for the wisdom of the Perl Monks concerning the following question:

Hey Everyone, I have a really easy question, I'm sure I'm just messing up the syntax, but I can't seem to find any great info on the web.

I want to use a variable in printf's "%s" formatting instead of a static number for the amount of spaces.

So instead of: printf "%5s",some_string;

I'd like to do:

$space = 5;

printf "%($space)s",some_string;

Thanks a lot!

Replies are listed 'Best First'.
Re: printf syntax
by BrowserUk (Pope) on Aug 13, 2009 at 17:55 UTC

    Two ways:

    1. Interpolate:

      You need to wrap the variable name in curlies to prevent the 's' being taken as a part of it:

      $space = 5; printf "%${space}s\n", 'x';; x
    2. Let printf fill in the value for you by using the '*' specifier:
      $space = 5; printf "%*s\n", $space, 'x';; x

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: printf syntax
by FunkyMonk (Chancellor) on Aug 13, 2009 at 17:51 UTC
    Use the special "*" width:
    printf "%*s", 10, $some_string;

    That will print your string, right justified and padded to 10 spaces. Use -10 if you want left justification.

Re: printf syntax
by kennethk (Abbot) on Aug 13, 2009 at 17:51 UTC
    The syntax printf "%${space}s", $some_string; should do what you want.
      Thanks for the prompt reply! I really appreciate your help. This works for me!
Re: printf syntax
by QM (Parson) on Aug 13, 2009 at 20:53 UTC
    The printf docs are covered under sprintf.

    Quantum Mechanics: The dreams stuff is made of

      In addition to the fact that the docs for printf already say the documentation for the format string is in sprintf, adding curlies to disambiguate during interpolation is documented in perldata and has nothing to do with either printf or sprintf.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://788396]
Approved by kennethk
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2018-07-19 19:50 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (417 votes). Check out past polls.