Home > Archive > PERL Beginners > August 2006 > Can't create 2d array in Perl
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Can't create 2d array in Perl
|
|
| Gregg Allen 2006-08-29, 9:57 pm |
| Hi:
I would like to read a tab delimited text file created in Excel into
a 2d array. I don't understand why the following doesn't work. The
$i and $j, along with the print statement, are only for debugging
purposes.
It prints:
Can't use string ("") as an ARRAY ref while "strict refs" in use at
file_vars.pl line 30, <FH> line 2.
Gregg Allen
****************************************
*****************
#!/usr/bin/perl -w
use strict;
my @arr ;
my $i = $ARGV[0];
my $j = $ARGV[1];
print $i . " \t" . $j . "\n";
open(FH,"<0817L.txt") or die "cannot open !$\n";
while(<FH> )
{
push @arr , split /\t/ ;
}
print $arr[$i][$j];
| |
|
| Gregg Allen wrote:
> I would like to read a tab delimited text file created in Excel into
> a 2d array. I don't understand why the following doesn't work.
> It prints:
> Can't use string ("") as an ARRAY ref while "strict refs" in use at
> file_vars.pl line 30, <FH> line 2.
[snip]
> while(<FH> )
> {
> push @arr , split /\t/ ;
You just need a pair of "[" ... "]" around "split /\t/", that's all:
push @arr, [ split /\t/ ];
(for reference --> see perldoc perldsc)
> }
>
> print $arr[$i][$j];
| |
| Mumia W. 2006-08-29, 9:57 pm |
| On 08/29/2006 07:01 PM, Gregg Allen wrote:
> Hi:
>
>
> I would like to read a tab delimited text file created in Excel into a
> 2d array. I don't understand why the following doesn't work. The $i
> and $j, along with the print statement, are only for debugging purposes.
>
> It prints:
>
>
> Can't use string ("") as an ARRAY ref while "strict refs" in use at
> file_vars.pl line 30, <FH> line 2.
>
> Gregg Allen
>
> ****************************************
*****************
> #!/usr/bin/perl -w
>
>
> use strict;
>
>
> my @arr ;
>
> my $i = $ARGV[0];
> my $j = $ARGV[1];
>
> print $i . " \t" . $j . "\n";
>
>
> open(FH,"<0817L.txt") or die "cannot open !$\n";
>
> while(<FH> )
> {
>
> push @arr , split /\t/ ;
>
> }
>
>
> print $arr[$i][$j];
>
>
I'm really about what $i and $j are supposed to be,
but I might do it this way:
use strict;
use warnings;
use File::Slurp;
use Data::Dumper;
my @arr = map [ split /\t/ ], read_file('0817L.txt');
print Dumper(\@arr);
__END__
WARNING: UNTESTED CODE
| |
| Jeff Pang 2006-08-29, 9:57 pm |
|
>
>while(<FH> )
>{
>
>push @arr , split /\t/ ;
>
>}
>
>
Hello,
Here you don't create a 2d array.Maybe you want this:
while(<FH> ) {
push @arry,[split/\t/];
}
Then each element of @arry is a anonymous array.You can access the anonymous array's elements as:
print $arry[0]->[0];
Hope this helps.
--
Jeff Pang
NetEase AntiSpam Team
http://corp.netease.com
|
|
|
|
|