http://qs321.pair.com?node_id=260679

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.