Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Can you change the format pad character?

by dextius (Monk)
on May 25, 2003 at 09:06 UTC ( [id://260679]=perlquestion: print w/replies, xml ) Need Help??

dextius has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to modify the default pad character of the format function from space to something user defined? Side question: If you can not, what is the fastest way of padding (to a fixed length) multiple columns of data?
  • Comment on Can you change the format pad character?

Replies are listed 'Best First'.
•Re: Can you change the format pad character?
by merlyn (Sage) on May 25, 2003 at 12:18 UTC
    The format directive is pretty frozen and inflexible, although it's always worthy of asking a question because there might be some arcane mechanism to influence it to get your desired behavior. In this case, no. {grin}

    However, this piece of code can be dropped in to your program rather easily:

    sub pad_string { my $string = shift; my $desired_length = shift; my $pad_character = shift || " "; substr($string,0,0) = $pad_character x ($desired_length - length $st +ring); $string; }

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      At least when the padding is whitespace (which the OP seemed to want), is this solution better than using (s)printf? For ex:

      my $string = 'foo'; my $len = 15; $string = sprintf "%${len}s", $string; print $string;

      Please note: Don't get me wrong. For fear of fire and brimstone, the Novice that I am would not presume to criticise merlyn. It's just that I've been playing with (s)printf recently, prompting me to change a few old progs from, like:

      print ' ' x ( 23 - length $foo ), $foo;

      to:

      printf '%23s', $foo;

      Have I been I wrong or (more likely), AIMS (Am I Missing Something)?

      dave

        You said:
        At least when the padding is whitespace (which the OP seemed to want)
        But OP said:
        Is it possible to modify the default pad character of the format function from space to something user defined?
        Yes, had the original question been about padding whitespace, I certainly would have preferred sprintf. But it was precisely not about that, hence my solution.

        -- Randal L. Schwartz, Perl hacker
        Be sure to read my standard disclaimer if this is a reply.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-18 22:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found