简体   繁体   English

Perl中的2D阵列参考

[英]2D Array reference in Perl

I am trying to do a subprogram in Perl that will load data into 2D array: 我试图在Perl中做一个子程序,它将数据加载到2D数组中:

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: 示例文件,我们可以将其命名为x:

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

executing script: 执行脚本:

cat x | perl name

and the answer should be "az" instead of "zz". 答案应该是“ az”而不是“ zz”。 I know that it must be something wrong with \\@temp, but I do not have idea how to make it correct. 我知道\\ @temp一定有问题,但是我不知道如何使其正确。 Does anyone could help me? 有人可以帮助我吗?

Regards 问候

For the sake of having a self-contained example, I replaced STDIN with DATA : 为了提供一个独立的示例,我用DATA替换了STDIN

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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