I am trying to write a simple Perl script that reads a *.csv, places the rows of the *.csv file in a two-dimensional array, prints an item out of the array, and prints a row of the array.
#!/usr/bin/perl
use strict;
use warnings;
open(CSV, $ARGV[0]) || die("Cannot open the $ARGV[0] file: $!");
my @row;
my @table;
while(<CSV>) {
@row = split(/\s*,\s*/, $_);
push(@table, @row);
}
close CSV || die $!;
foreach my $element ( @{ $table[0] } ) {
print $element, "\n";
}
print "$table[0][1]\n";
When I run this script I receive the following error and nothing prints:
Can’t use string ("1") as an ARRAY ref while "strict refs" in use at ./scripts.pl line 16.
I have looked in a number of other forums and am still not sure how to fix this issue. How can fix I this?
You aren’t creating a two-dimensional array (an AoA or “Array of Arrays” in Perl-parlance). This line:
appends the data in
@rowto@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:While using
splitis okay for trivial CSV files, it’s woefully inadequate for anything else. Use a module like Text::CSV_XS instead: