Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

•Re: Can you change the format pad character?

by merlyn (Sage)
on May 25, 2003 at 12:18 UTC ( [id://260686]=note: print w/replies, xml ) Need Help??


in reply to Can you change the format pad character?

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.

Replies are listed 'Best First'.
Re: •Re: Can you change the format pad character?
by Not_a_Number (Prior) on May 26, 2003 at 21:28 UTC

    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.

        Doh!

        How did I manage to read the exact opposite of what was said?

        Sorry...

        dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-23 22:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found