简体   繁体   中英

2D Array reference in Perl

I am trying to do a subprogram in Perl that will load data into 2D array:

sub load {
    my $separator = shift;
    my $i = 0;

    while(<STDIN>) {
        @temp = split(/$separator/, $_);
        @arr[$i] = \@temp;
        $i++;
    }
    return @arr;
}

@array = load(":");
print "$array[0][0] $array[1][0]";

example file, we can name it x:

a:b:c:d
z:x:c:v

executing script:

cat x | perl name

and the answer should be "az" instead of "zz". I know that it must be something wrong with \\@temp, but I do not have idea how to make it correct. Does anyone could help me?

Regards

For the sake of having a self-contained example, I replaced STDIN with DATA :

use warnings;
use strict;

sub load {
    my $separator = shift;
    my @arr;

    while(<DATA>) {
        chomp;
        my @temp = split(/$separator/, $_);
        push @arr, \@temp;
    }
    return @arr;
}

my @array = load(":");
print "$array[0][0] $array[1][0]\n";

__DATA__
a:b:c:d
z:x:c:v

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM