in reply to Printing an array in columns - improvements?

#!/usr/bin/perl use strict; use warnings 'all'; my @array = qw/one two three four five six seven eight nine ten/; my $cols = 3; my $max = -1; $_ > $max && ($max = $_) for map {length} @array; while (@array) { print join " " => map {sprintf "%-${max}s" => $_} splice @array => 0, $cols; print "\n"; }

Abigail

Replies are listed 'Best First'.
Re: Re: Printing an array in columns - improvements?
by BrowserUk (Patriarch) on Jul 18, 2002 at 16:57 UTC

    Could I prevail upon you (or anyone) to explain the three uses of the => operator in your answer?

    I seen this a few times now, and have tried to understand it, but have to admit that I am completely foxed by it.

    Thanks.

      Well, its not from the horses mouth, but heres a quick explanation.

      Basically all Abigail-II is doing is conceptually breaking up the code by using the fat comma. Dont forget that semantically the => is equivelent to a comma (,) with the added nicety that if the item on the lhs is a bareword the bareword is automatically quoted.

      print join " " => map {sprintf "%-${max}s" => $_} splice @array => 0, $cols;
      is the same thing as
      print join " " , map {sprintf "%-${max}s", $_} splice @array, 0, $cols;
      as well as
      print join(" ",map {sprintf "%-${max}s",$_}splice(@array,0,$cols));
      The easiest to read is the first I think you'll agree. (although i dont know that i would have used a fat comma in the sprintf() call but whatever ;-)

      Yves / DeMerphq
      ---
      Writing a good benchmark isnt as easy as it might look.