I found an example in an O'Reilly book a little weird:
@backwards = reverse qw/ yabba dabba doo /;
print "list context: @backwards\n";
$backward = reverse qw/ yabba dabba doo /;
print "scalar1 context: $backward\n";
$notbackward = qw/ yabba dabba doo /;
print "scalar2 context: $notbackward\n";
print "print context: ",reverse qw/ yabba dabba doo /;
print "\n";
The output is:
list context: doo dabba yabba
scalar1 context: oodabbadabbay
scalar2 context: doo
print context: doodabbayabba
The one I do not understand is the scalar1
context:
The book says 'reverse something' gives a list context, so I guess qw/ yabba dabba doo /
is seen as a list and reverse qw/ yabba dabba doo /
as ('doo', 'dabba', 'yabba').
So comes the $backward = something
which implies something is a scalar, so I was expecting the result 'doo dabba yabba', but it is différent: 'oodabbadabbay'.
I thought, the reason was because one cannot set a list to a scalar directly. So I made the scalar2
test: only the latest item in the list is printed. Why? Why not in the scalar1 test?
How do the scalar tests output work?
For the line:
You are requesting a scalar here from reverse. The perldoc for reverse says:
So it returns each of the letters reversed.
For $notbackward = qw/ yabba dabba doo /; the perldoc for qw// says:
So requesting the scalar only returns the last item in the list.