Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't do "shift subroutine_name()" in Perl?

Tags:

perl

Why does this code return an Not an ARRAY reference error?

sub Prog {
    my $var1 = 1;
    my $var2 = 2;
    ($var1, $var2);
}

my $variable = shift &Prog;
print "$variable\n";

If I use an intermediate array, I avoid the error:

my @intermediate_array = &Prog;
my $variable = shift @intermediate_array;
print "$variable\n";

The above code now outputs "1".

like image 618
Alexander Avatar asked Dec 01 '22 00:12

Alexander


2 Answers

The subroutine Prog returns a list of scalars. The shift function only operates on an array. Arrays and lists are not the same thing. Arrays have storage, but lists do not.

If what you want is to get the first element of the list that Prog returns, do this:

sub Prog {
    return ( 'this', 'that' );
}

my $var = (Prog())[0];
print "$var\n";

I changed the sub invocation to Prog() instead of &Prog because the latter is decidedly old style.

You can also assign the first element to a scalar like others are showing:

my ($var) = Prog();

This is roughly the same as:

my ($var, $ignored_var) = Prog();

and then ignoring $ignored_var. If you want to make it clear that you're ignoring the second value without actually giving it a variable, you can do this:

my ($var, undef) = Prog();
like image 155
Andy Lester Avatar answered Dec 05 '22 06:12

Andy Lester


Prog is returning a list, not an array. Operations like shift modify the array and cannot be used on lists.

You can instead do:

my ($variable) = Prog; # $variable is now 1: 
                       # Prog is evaluated in list context 
                       # and the results assigned to the list ($variable)

Note that you don't need the &.

like image 45
user52889 Avatar answered Dec 05 '22 04:12

user52889