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.
print "The time is ",localtime(); printf "\nor do you prefer %s\n\n", scalar localtime(); $a = "1234"; $b = "4321"; print "Hmm '$a' eq reverse '$b'\n" if $a eq reverse $b; print "But reverse \$b = ", reverse $b; print "\nWhich is not equal to \$a = ", $a; # assign a scalar context to reverse print "\n\nApplying scalar context to reverse\n"; $b = "4321"; $b = reverse $b; print "Now \$b = '$b', which is reversed\n"; # you can assign scalar context to reverse like this to $b = "4321"; printf "Here too reverse \$b = '%d'\n", scalar reverse $b; printf "And also here reverse \$b = '%d'\n", eval reverse $b;
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Reverse in scalar context
by John M. Dlugosz (Monsignor) on Jul 12, 2001 at 01:02 UTC | |
by Abigail (Deacon) on Jul 12, 2001 at 01:12 UTC | |
by John M. Dlugosz (Monsignor) on Jul 12, 2001 at 01:15 UTC | |
by tachyon (Chancellor) on Jul 12, 2001 at 01:44 UTC | |
|
Re: Reverse in scalar context
by dragonchild (Archbishop) on Jul 12, 2001 at 00:55 UTC |