Search code examples
perlreferencedereference

Dereferencing values from an array to declared variables in one line


To retrieve arguments from a function call I usually do

use strict;
use warnings;

foo([1,2],[3,4]);

sub foo{
    my ($x, $y) = @_;
    ...
}

In the example, $x and $y are now references to an array each. If I want to use the variables inside these arrays easily I dereference them first.

...
my ($x1, $x2) = @{$x}[0,1];
# ...same for $y

I'm wondering if there is a way to dereference the arguments in @_ (or, indeed, any other array) and return them to a list of declared variables in just one line?


Solution

  • foo ( [1,2], [3,4] );
    
    sub foo {
    
        my ( $x1, $x2, $y1, $y2 ) = map @$_, @_;
    
        ...
    }
    

    The map takes @_ and dereferences each of its elements into an array with the @$_ operation.

    One could also use List::Gen's deref or d functions to achieve the same goal.