Please could you explain this apparently inconsistent behaviour to me:
use strict;
my @a;
print "a" x 2; # this prints: aa
@a = "a" x 2; print @a; # this prints: aa
print ("a") x 2; # this prints: a
@a = ("a") x 2; print @a; # this prints: aa
Shouldn't the last one print a single 'a'?
Edit: Ok so now this is kind of making more sense to me: "Binary "x" is the repetition operator...In list context, if the left operand is enclosed in parentheses or is a list formed by qw/STRING/, it repeats the list." perlop
This is as clear as mud to me (binary x - why use the word binary? Is there a denary X?) But anyway: @a = ("a") x 2 # seems to be in list context, in that we have an array at the beginning - an array is not a list, but it contains a list, so I think we probably have a list context, (not an array context although they might be synonymous).
i suppose the "left operand" is ("a"). (It's either that or @a). perlop doesn't say what an operand actually is, querying perldoc.perl.org gives "No matches found", and googling gives "In computer programming, an operand is a term used to describe any object that is capable of being manipulated." Like an array for instance.
So the left operand might be enclosed in brackets so maybe it should "repeat the list". The list is either: ("a") x 2
or it is: ("a")
If we repeated ("a") x 2
we would get ("a") x 2 ("a") x 2
. This doesn't seem right.
If we type: print $a[1]
we will get a single 'a', so "it repeats the list" means Perl turns ("a") x 2
into ("a", "a")
so we effectively get @a=("a", "a")
However, print ("a") x 2
does not get turned into ("a", "a")
. That's because print is a "list operator" with a high precedence. So there we effectively get: (print ("a")) x 2
An array is a term so it also has a high precedence, but @a=stuff involves the assignation operator = which has a relatively low precedence. So it's quite different from print.