Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 840
Bob Bryan Avatar asked Oct 11 '25 18:10

Bob Bryan


2 Answers

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];
    #   ...
}
like image 101
RobEarl Avatar answered Oct 15 '25 07:10

RobEarl


my $arrays_ref = [ [1,2], [3,4] ];

for my $array_ref (@$arrays_ref) {

    printf "%s\n", $array_ref->[0];
}
like image 42
Pavel Vlasov Avatar answered Oct 15 '25 06:10

Pavel Vlasov