On 11/30/2011 03:06 PM, Jeswin wrote:
I've been trying to figure out how to print 2 arrays into 2 columns. I
came across this code and it works but gives me a problem in the
output.
sub transpose {
     map { my $i = $_; [ map $_->[ $i ], @_ ] } 0 .. $#{ $_[0] }
}
print "@$_\n" for transpose \( @unknown_abs, @unknown_conc  );

Those nested maps are making me think too hard, and I'm still not sure I understand what they're doing. I'd rather debug the KISS version:

$ cat print-arrays-side-by-side.pl
#!/usr/bin/perl
use strict;
use warnings;
my @array1 = ("Fred", "Barney", "Wilma", "Betty");
my @array2 = ("Flintstone", "Rubble", "Flintstone"); ### Oops!
print "C style:\n";
for (my $i = 0; $i < @array1; $i++) {
    print join " ", "\t", $array1[$i], $array2[$i], "\n";
}
print "More Perlish:\n";
print join " ", "\t", $array1[$_], $array2[$_], "\n" for 0 .. $#array1;

$ perl print-arrays-side-by-side.pl
C style:
         Fred Flintstone
         Barney Rubble
         Wilma Flintstone
Use of uninitialized value in join or string at print-arrays-side-by-side.pl line 8.
         Betty
More Perlish:
         Fred Flintstone
         Barney Rubble
         Wilma Flintstone
Use of uninitialized value in join or string at print-arrays-side-by-side.pl line 11.
         Betty


Note that the code doesn't check for equal length arrays (or undefined elements, or reference elements, or ...). @array1 has one more element than @array2, thus the warning:

Use of uninitialized value in join or string at print-arrays-side-by-side.pl line 11.


Try inserting "undef" as an element and see what happens. What about a reference, such as "\0"?


If you're going to deal with Perl, "Learning Perl" is the place to start:

    http://shop.oreilly.com/product/0636920018452.do


HTH,

David

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to