Why is assigning a list of variables inconsistent?

To save 2 values ​​from the list returned by the subset and throw the third one, you can:

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

and works as expected (in both perl5 and perl6). If you want only the first, however,

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

... you will get the whole list. It seems contradictory - why inconsistency?

+8
perl6
source share
2 answers

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

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

Note that although this works like declarations, return containers that are first-class objects that can be placed on lists, however, you are doing this “wrong”:

Appointments must read

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

and

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

Also note that the pairs on the right side are also redundant (this is the comma that builds the list); more idiomatic versions will be

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

and

 my ($first) = 1, 2, 3; 
+9
source share
 (my $first, ) = (1,2,3); dd $first; # OUTPUT«Int $first = 1␤» 

In the first example, you assign a list (or part of it) to the list of containers. Your second example does exactly what you are asking for. A list of values ​​is assigned to one container. In Perl 5, the list is created in brackets (in this case), which results in Perl 6 creating the list with commas. The latter is used in my example to get what is required.

I would say Perl 5, which is incompatible, because sometimes lists are created with commas, brackets or parentheses.

 my ($first,$,$third) = (1,2,3); dd $first, $third; # OUTPUT«Int $first = 1␤Int $third = 3␤» 

You can skip one or more list items by adding anonymous state variables. It also shortens your first example.

 my $first,$ = 1,2,3; dd $first; # OUTPUT«Any $first = Any␤» 
+6
source share

All Articles