David M. Karr David M. Karr - 7 months ago 10
Perl Question

Assign multiple local vars to array entries in perl

In Perl, I've always been confused about how to cleanly assign multiple local variables from array entries.

I use the following syntax in subs all the time, so I'm somewhat familiar with it:

my ($var1, $var2) = @_


but other variations of this confuse me. For instance, I have the following code that works:

for my $ctr (0 .. $#matchingLines) {
my $lineNo = $matchingLines[$ctr][0];
my $text = $matchingLines[$ctr][1];


Where "
@matchingLines
" is an array of two-element arrays.

I wish I could convert the last two lines to the obvious:

my ($lineNo, $text) = $matchingLines[$ctr];


That of course does not work. I've tried numerous variations, but I can't find anything that works.

Answer

It sounds like you have an array of arrays. this means that the inner arrays will be array references. If you want to allocate them to vars then you need to derference them.

use strict;
use warnings;
my @matchingLines = (['y','z'],['a','b']);
for my $ctr (0 .. $#matchingLines) {
    my ($lineNo, $text) = @{$matchingLines[$ctr]};
    print "#Array index: $ctr - lineno=$lineNo - text=$text\n"
}

this produces the output

#Array index: 0 - lineno=y - text=z
#Array index: 1 - lineno=a - text=b