Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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!

Comment on printf syntax
Re: printf syntax
by kennethk (Monsignor) 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 FunkyMonk (Canon) 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 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 QM (Vicar) on Aug 13, 2009 at 20:53 UTC
    The printf docs are covered under sprintf.

    -QM
    --
    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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://788396]
Approved by kennethk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (9)
As of 2014-11-24 22:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (147 votes), past polls