简体   繁体   中英

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

I have the following Perl code:

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. I am trying to process each element in the array pointed to by $TransRef. $TransArrRef should obtain a reference to an array. I want to assign the first value within that array to $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 . 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.

Also, $#$TransRef gives you the last element in the array so you'd need <= rather than just < . Or use this Perl style loop:

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:

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 

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