Assign multiple local vars to array entries in perl

时间:2016-04-21 21:53:32

标签: arrays 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.

2 个答案:

答案 0 :(得分:8)

Just dereference the array ref:

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

Check out Perl Data Structures Cookbook for additional examples.

答案 1 :(得分:2)

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