How to print a Perl 2-dimensional array?
You aren't creating a two-dimensional array (an AoA or "Array of Arrays" in Perl-parlance). This line:
push(@table, @row);
appends the data in @row
to @table
. You need to push a reference instead, and create a new variable each time through the loop so that you don't push the same reference repeatedly:
my @table;
while(<CSV>) {
my @row = split(/\s*,\s*/, $_);
push(@table, \@row);
}
While using split
is okay for trivial CSV files, it's woefully inadequate for anything else. Use a module like Text::CSV_XS instead:
use strict;
use warnings;
use Text::CSV_XS;
my $csv = Text::CSV_XS->new() or die "Can't create CSV parser.\n";
my $file = shift @ARGV or die "No input file.\n";
open my $fh, '<', $file or die "Can't read file '$file' [$!]\n";
my @table;
while (my $row = $csv->getline($fh)) {
push @table, $row;
}
close $fh;
foreach my $row (@table) {
foreach my $element (@$row) {
print $element, "\n";
}
}
print $table[0][1], "\n";
my @arr = ( [a, b, c],
[d, e, f],
[g, h, i],
);
for my $row (@arr) {
print join(",", @{$row}), "\n";
}
prints
a,b,c
d,e,f
g,h,i
Edit: I'll let others get the credit for catching the wrong push.
You need 2 changes:
- use local variable for row
- use references for array you put into
@table
So your program should look this:
#!/usr/bin/perl
use strict;
use warnings;
open(CSV, $ARGV[0]) || die("Cannot open the $ARGV[0] file: $!");
my @table;
while(<CSV>) {
my @row = split(/\s*,\s*/, $_);
push(@table, \@row);
}
close CSV || die $!;
foreach my $element ( @{ $table[0] } ) {
print $element, "\n";
}
print "$table[0][1]\n";