9

You can declare a list of variables and assign them some value in Perl 6

my ($a, $b) = 33,44 # $a will be 33 and $b 44

However, if you try to assign the value following the declaration of the variable the values will be silently dropped

my ($a = 44, $b = 33); 
say $a, $b; #OUTPUT: «(Any)(Any)␤» 

It gets weirder from there, since

 my ($a = 44, $b);

fails with:

===SORRY!=== Error while compiling /tmp/G7JgLMe1Wq
Cannot put required parameter $b after optional parameters

and

my ($a, $b = 33);

will have the same result as assigning any of them together.

This behavior is confusing to me. Should it issue a warning? Should the first expression also yield the same error about optional parameters? Should we document it as a trap? All of the above?

Pat
  • 36,282
  • 18
  • 72
  • 87
jjmerelo
  • 22,578
  • 8
  • 40
  • 86

1 Answers1

9

The behaviour can be understood from knowing that along with assignment syntax, there's also signature binding syntax, where the left hand side has basically all of the features of parameters in a signature (minus a couple NIY features):

    <Zoffix__> m: my ($a, $b = 33) := \(); dd [$a, $b]
    <camelia> rakudo-moar 472f6e484: OUTPUT: «Too few positionals passed to '<unit>'; expected 1 or 2 arguments but got 0␤  in block <unit> at <tmp> line 1␤␤»
    <Zoffix__> m: my ($a, $b = 33) := \(100); dd [$a, $b]
    <camelia> rakudo-moar 472f6e484: OUTPUT: «[100, 33]␤»
    <Zoffix__> m: my ($a, $b = 33) := \(100, 200); dd [$a, $b]
    <camelia> rakudo-moar 472f6e484: OUTPUT: «[100, 200]␤»

So what happens is you declare optional parameters that have default values. That's why your later example is talking about required parameters; you can't put requireds after optionals in routine signatures either. However, since you're not actually performing any binding, the variables remain unassigned.

will be silently dropped

We can probably implement some heuristics to detect this case and warn the user about it when the LHS looks like a signature case and the initializer is missing. Filed this as R#1864.