Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is assignment to a list of variables inconsistent?

Tags:

raku

To save 2 values from a list returned by a sub and throw the third away, one can;

(my $first, my $second) = (1, 2, 3);
print $first, "\n";
print $second, "\n";
exit 0;

and it works as expected (in both perl5 and perl6). If you want just the first however;

(my $first) = (1, 2, 3);
print $first, "\n";
exit 0;

... you get the whole list. This seems counter-intuitive - why the inconsistency?

like image 862
Marty Avatar asked Mar 14 '16 23:03

Marty


1 Answers

This should be due to the single argument rule. You get the expected behaviour by adding a trailing ,:

(my $first,) = (1, 2, 3);

Note that while this works as declarations return containers, which are first-class objects that can be put in lists, you're nevertheless doing it 'wrong':

The assignments should read

my ($first, $second) = (1, 2, 3);

and

my ($first) = (1, 2, 3);

Also note that the parens on the right-hand side are superfluous as well (it's the comma that does list construction); the more idiomatic versions would be

my ($first, $second) = 1, 2, 3;

and

my ($first) = 1, 2, 3;
like image 75
Christoph Avatar answered Dec 01 '22 21:12

Christoph