简体   繁体   English

如何从引用数组访问Perl数组中的元素

[英]How to access an element in a Perl array from a reference to an array of references

I have the following Perl code: 我有以下Perl代码:

package CustomerCredit;
#!/usr/local/bin/perl
use 5.010;
use strict;

my $TransRef = @_; # This code comes from a sub within the package.
my ($Loop, $TransArrRef, $TransID);
for ($Loop = 0; $Loop < $$#TransRef; $Loop++)
{
   $TransArrRef = $$TransRef[$Loop]; # Gets a ref to an array.
   $TransID = $$TransArrRef[0];  # Try to get the first value in the array.
   # The above line generates a compile time syntax error.
   ...
}

$TransRef is a reference to an array of references to arrays. $ TransRef是对数组引用数组的引用。 I am trying to process each element in the array pointed to by $TransRef. 我正在尝试处理$ TransRef指向的数组中的每个元素。 $TransArrRef should obtain a reference to an array. $ TransArrRef应获取对数组的引用。 I want to assign the first value within that array to $TransID. 我想将该数组中的第一个值分配给$ TransID。 But, this statement generates a compile syntax error. 但是,此语句会生成编译语法错误。

I must be doing something wrong, but can not figure out what it is. 我必须做错事,但无法弄清楚它是什么。 Can anyone help? 有人可以帮忙吗?

The syntax error is coming from $$#TransRef which should be $#$TransRef . 语法错误来自$$#TransRef ,它应该是$#$TransRef By misplacing the # you accidentally commented out the rest of the line leaving: 通过错放#你意外地评论了剩余的线路离开:

for ($Loop = 0; $Loop <= $$
{
   $TransArrRef = $$TransRef[$Loop];
   ...
}

$$ is ok under strict as it gives you the process id leaving the compiler to fail further down. $$strict因为它为您提供进程ID,让编译器进一步失败。

Also, $#$TransRef gives you the last element in the array so you'd need <= rather than just < . 此外, $#$TransRef为您提供数组中的最后一个元素,因此您需要<=而不是< Or use this Perl style loop: 或者使用这个Perl样式循环:

for my $loop (0 .. $#$TransRef) {
    $TransID = $TransRef->[$loop]->[0];
    #   ...
}
my $arrays_ref = [ [1,2], [3,4] ];

for my $array_ref (@$arrays_ref) {

    printf "%s\n", $array_ref->[0];
}

You can use foreach as well: 你也可以使用foreach

my @array = ('val1', 'val2', 'val3') ;
my $array_ref = \@array ;

print "array size is $#{$array_ref} \n" ;

foreach $elem (@$array_ref) {
   print "$elem \n"
}

Outputs: 输出:

array size is 2 
val1 
val2 
val3 

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

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