Scalar and List context in Perl -
1 @backwards = reverse qw(yabba dabba doo); 2 $backwards = reverse qw(yabba dabba doo); 3 4 print @backwards; #gives doodabbayabba 5 print $backwards."\n"; #gives oodabbadabbay 6 print @backwards."\n"; #gives 3
in above code why line 6
give 3 output? why convert scalar context if concatenated \n?
thanks
your question "why @backwards in scalar context in line 6", begs question, "how can determine term's context?".
context determined "what around" (i.e. "context") term.
how can determine term's context? looking @ operator/function using term.
what steps follow figure out context @backwards if didn't have helpful stackoverflow folks around tell context?
here have
print @backwards."\n"
so there 2 operators/functions. how know 1 provides context @backwards? consulting precedence. near top of perlop.pod have perl's precedence chart (print "list operator"):
left terms , list operators (leftward) ... left + - . ... nonassoc list operators (rightward)
oh great, need know whether print leftward or rightward. consulting "terms , list operators (leftward)" section in perlop (right after precedence list) see print rightward here, because have not enclosed arguments in parenthesis.
so concatenation higher precedence, concatenation provides context @backwards.
next step check docs (perlop again) concatenation:
binary "." concatenates 2 strings.
strings scalars, binary "." concatenates 2 scalars.
and have it!
@backwards has scalar context because concatenation provides scalar context each of operands.
woo. easy, wasn't :-)
Comments
Post a Comment