I was teaching an "Introduction to Perl" course the other day, and one of the students had this code (I've paraphrased, as it were):@a = qw(a b c d e); @b = @a; # @b contains (a b c d e) $b = @a; # $b is 5, as the "=" is overloaded by context
@a = qw(a b c d e); $b = @a[1,3]; print $b
Now, My understanding is that the code would print "2", being the number of elements in the array-slice. it prints "d"
Indeed, my slides make the point that @array[$n] is a one-element array, not a scalar, thus $b=@array[$n] will set $b to 1, not the value of the array element ($b=$array[$n])!prints "b"@a = qw(a b c d e); $b = @a[1]; print $b
prints 1@a = qw(a b c d e); @b = @a[1]; $b = @b print $b
WTF?
So, I tried forcing a scalar context on the assignement:
@a = qw(a b c d e); $b = scalar @a[1,3]; print $b
.... still prints "d"!
Switch the array-slice around, and we still get the last element in the scalar:@a = qw(a b c d e); $b = @a[3,1]; print $b
prints "b"
Can someone explain why?In reply to Confused as to why the "casting context" is mis-behaving by kiz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |