good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
Reverse in scalar contextby tachyon (Chancellor) |
on Jul 12, 2001 at 00:45 UTC ( [id://95847]=perlquestion: print w/replies, xml ) | Need Help?? |
tachyon has asked for the wisdom of the Perl Monks concerning the following question: particle was talking to me about reverse and not being able to get it to work in scalar context. The problem with reverse is the classic Perl scalar versus list context one. Many perl functions can return either a scalar or a list, depending on how they are called. localtime() is a common one that can return suprising results if you wanted the scalar human readable form and insted call it in list context. Reverse to exhibits some interesting behaviour on the surface.
This prints: The time is 4434612610141920 or do you prefer Thu Jul 12 06:34:44 2001 Hmm '1234' eq reverse '4321' But reverse $b = 4321 Which is not equal to $a = 1234 Applying scalar context to reverse Now $b = '1234', which is reversed Here too reverse $b = '1234' And also here reverse $b = '1234' In the example where reverse seems to fail it actually does not. Perl assumes list context in the print and thus reverses the one element list containing $b - this of course does not reverse the content of $b. To get it to work you need to force scalar context. It took me a while to get to grips with this behaviour. cheers tachyon s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print
Back to
Seekers of Perl Wisdom
|
|