I have had this question for a while.
Assuming I have a simple array,
my @arr;
foreach my $i (0..$#arr){
print "\$arr[$i] = '$arr[$i]'\n";
}
$#arr simply returns the last index of the array
however, what happens if I want to use it for something more complex like?:
foreach my $i (0..$#@{$someHash{$}[$b]{$c}});
sure, I can write it as
foreach my $i (0..(scalar(@{$someHash{$}[$b]{$c}})-1));
But that just makes the code even more complex.
So my question is, can the $# be used for anything else other than a simple array( references, a list returned from a function call, etc…) and if so, how?
Thanks
Yes, you want:
If possible, though, I generally prefer
an index value is rarely as useful as the value stored in the array. Typically, if I need both, I add a counter instead:
and for clarity, I will also pre-assign the complex variable in the loop:
Just because you can do some things in one line in Perl doesn’t necessarily mean you should.