Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
laziness, impatience, and hubris
 
PerlMonks  

Re: printing unequal sized lists side by side

by nvivek (Priest)
on May 28, 2011 at 05:14 UTC ( #907102=note: print w/ replies, xml ) Need Help??


in reply to printing unequal sized lists side by side

You can get it by following way

use strict; use warnings; my @array1=(1 .. 20); my @array2=('a' .. 'e' ); my $max_array_length=(scalar(@array1) > scalar(@array2)) ? scalar(@arr +ay1) : scalar(@array2); for(my $index=0; $index<$max_array_length; $index++) { print $array1[$index] if $array1[$index]; print ","; print $array2[$index] if $array2[$index]; print "\n"; }


Comment on Re: printing unequal sized lists side by side
Download Code
Re^2: printing unequal sized lists side by side
by ww (Bishop) on May 28, 2011 at 10:59 UTC
    + + (esp for the economy of solving OP's problem withOUT adding module overhead) ...but with a minor nitpick.

    Consider your output, if @array1 and @array2 are swapped, making @array2 the longer of the two.

    But one can make that output slightly more elegant (a matter of taste, of course; YMMV) by using the ternary again in print statements which make visual allowance for non-existent indices:

    for(my $index=0; $index<$max_array_length; $index++) { print $array1[$index] ? $array1[$index] : ' '; print ", "; print $array2[$index] ? $array2[$index] : '-'; print "\n"; }
      Thanks. This is close to what I had been doing and it helps greatly to see it in a post ;)
      I do tend to prefer to avoid adding modules if only for peace of mind that the customer can push the scripts around systems w/o fear of it breaking.

      I appreciate the help :)

      Instead of the ternary operator, might I recommend the "defined-or" test instead. It's more succinct and it doesn't fail on a value of '0'.

      print $array1[$index] // ' ';

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2014-04-19 20:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (483 votes), past polls