4

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?

1

3 Answers 3

4

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];
    #   ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

there's also an error in my $TransRef = @_; which will assign a number (the number of elements in @_) to $TransRef
2
my $arrays_ref = [ [1,2], [3,4] ];

for my $array_ref (@$arrays_ref) {

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

Comments

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.