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

Why Not an ARRAY referencedoes this code return an 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".

+4
source share
2 answers

The routine Progreturns a list of scalars. The shiftfunction only works with an array. Arrays and lists are not the same thing. Arrays have storage, but no lists.

If you want the first list item returned Prog, do the following:

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

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

I replaced the helper call with Prog()instead &Prog, because the latter is clearly an old-fashioned style.

, :

my ($var) = Prog();

, :

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

$ignored_var. , , , :

my ($var, undef) = Prog();
+13

Prog , . shift .

:

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

, &.

+7

All Articles