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

playing with formats today, i read Formats and Variables

which was great! because for my formatting needs, formline() seemed to be even better than format -- my desire was to loop through an array, and format each element into the line style -- a 60col wide line with centered text and | at each site

example: | centered text line! |

learning formline though, my code ended up as something like:

$^A = ''; $printIt = "+-----------------------+\n"; foreach $line (@lines){ formline("| \@|||||||||||||||||||| |\n",$line); } $printIt .= $^A; $printIt .= "+-----------------------+\n";

without the line "$^A = '';", running this again (its in a subroutine) churns out the last time's results

this seems kind of... messy... to me

is there a better way?
can i do this without nullifying $^A?
is it possible to do this (center, left/right justify text) with sprintf instead?
advice?

Replies are listed 'Best First'.
Re: sprintf vs formline
by Zaxo (Archbishop) on Sep 03, 2002 at 03:56 UTC

    You probably should localize $^A:

    sub foo { local $^A; my @lines = @_; my $printIt = "+-----------------------+\n"; foreach $line (@lines){ formline("| \@|||||||||||||||||||| |\n",$line); } $printIt .= $^A; $printIt .= "+-----------------------+\n"; return $printIt; }

    See perlvar for more details.

    After Compline,
    Zaxo

      that works well!

      I tried using 'my' earlier -- just because i'm in the habit of my vs local -- but that triggered an error

      never thought of trying local instead -- figured it would just spew an error as well.

      obviously, it didn't

        Local is used for "hiding" the current value of a package level (dynamic variable) for the duration of a scoped block. Note that duration means temporal and not the spatial aspect of a scoped block.

        (Well actually you can localize array indexes and hash entries in lexicals too, but people dont do this often.)

        Yves / DeMerphq
        ---
        Software Engineering is Programming when you can't. -- E. W. Dijkstra (RIP)

Re: sprintf vs formline
by Aristotle (Chancellor) on Sep 03, 2002 at 14:00 UTC
    You needn't use an extra variable either, btw.
    sub foo { local $^A = "+-----------------------+\n"; formline "| \@|||||||||||||||||||| |\n", $_ for @_; $^A .= "+-----------------------+\n"; return $^A; }

    Makeshifts last the longest.