将数组存储为关联数组中的值

Jag*_*ath 1 perl

我有一个问题,我需要一个数组作为关联数组中的值.

浏览下面的代码.在这里,我试图循环一个目录中的文件,更有可能超过1个文件可以具有相同的ctrno.所以,我想看看所有文件都有相同的内容ctrno.下面的代码$ctrno_hash[$ctrno] = @arr;在else条件下给出错误" ".同样的情况也适用于if条件.

我是否采用了正确的方法,还是可以采取不同的方式?

sub loop_through_files
{
    $file = "@_";
    open(INPFILE, "$file") or die $!;
    #print "$file:$ctrno\n";
    while (<INPFILE>)
    {
       $line .= $_;
    }
    if ($line =~ /$ctrno/ )
    {
       print "found\n";
       if ( exists $ctrno_hash[$ctrno])
       {
          local @arr = $ctrno_hash[$ctrno];
          push (@arr, $file);
          $ctrno_hash[$ctrno] =  @arr;
       }
       else
       {
          local @arr;
          push(@arr, $file);
          $ctrno_hash[$ctrno] =  @arr;
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*ger 5

我相信你想要的东西

$ctrno_hash[$ctrno] =  \@arr;
Run Code Online (Sandbox Code Playgroud)

这将把数组@arr变成一个array reference.

然后,您可以参考之前推送的数组引用

@{$ctrno_hash[$ctrno]}
Run Code Online (Sandbox Code Playgroud)

也就是说,如果$array_ref是数组引用,则构造@{ $array_ref }返回数组引用指向的数组.

现在,构造$ctrno_hash[$ctrno]实际上不是一个哈希,而是一个普通的数组.为了真正使它成为哈希,你需要大括号而不是方括号:

@{$ctrno_hash{$ctrno} } = \@arr;
Run Code Online (Sandbox Code Playgroud)

同样,您稍后将引用该数组

@{$ctrno_hash{$ctrno} }
Run Code Online (Sandbox Code Playgroud)

现在,说完了,你可以放弃if ... exists构造:

if ($line =~ /$ctrno/ )
{
   print "found\n";
   push @{$ctrno_hash{$ctrno}}, $file
}
Run Code Online (Sandbox Code Playgroud)