perl 6 variable same name different sigils inconsistent behavior

151 Views Asked by At

There seems to be some inconsistent behavior when variables of the same letter-name but different sigils are used:

> my $a="foo";
foo
> my @a=1,2
[1 2]
> say $a
foo               # this is what I have expected
> my $b = 1,2,3
(1 2 3)
> my @b = (0, $b.Slip)
[0 1]             # I expect to get [0 1 2 3]; (0, |$b) not work either
> say $b
1                 # I expect $b to be unchanged, (1,2,3), but it is now 1;
> say @a
[1 2]
> say @b
[0 1]
>

I am not sure why @a does not affect $a, whereas @b affects $b. Can someone please elucidate?

Thanks !!!

lisprog

1

There are 1 best solutions below

3
On

In Rakudo Perl 6 there is actually no relationship at all between $b and @b.

$b didn't change. It simply didn't get assigned what you thought it had been assigned. Looking at the documentation on Operator Precedence, you'll see that = (assignment) has a tighter precedence than the comma ,.

Also, you are using the REPL, which automatically prints out the return value of each statement. That return value may or may not be the same as the value assigned to a variable.

my $b = 1,2,3 actually is the same as
(my $b = 1),2,3 because = has tighter precedence than ,, meaning that effectively all but the first value is ignored

> (my $b = 1),2,3
(1 2 3)
> $b
1

If you want to assign a list to $b, then put parentheses around the list:

> my $b = (1,2,3)
(1 2 3)
> $b
(1 2 3)