Section 8.3. Reversing Scalars


8.3. Reversing Scalars

Use scalar reverse to reverse a scalar.

The reverse function can also be called in scalar context to reverse the characters in a single string:

     my $visible_email_address = reverse $actual_email_address;

However, it's better to be explicit that a string reversal is intended there, by writing:

      my $visible_email_address = scalar reverse $actual_email_address;

Both of these examples happen to work correctly, but leaving off the scalar specifier can cause problems in code like this:

     add_email_addr(reverse $email_address);

which will not reverse the string inside $email_address. That particular call to reverse is in the argument list of a subroutine. That means it's in list context, so it reverses the order of the (one-element) list that it's passed. Reversing a one-element list gives you back the same list, in the same order, with the same single element unaltered by the reordering.

In such cases, you're working against the native context, so you have to be explicit:

      add_email_addr(scalar reverse $email_address);

Rather than having to puzzle out contexts every time you want to reverse a string, it's much easierand more reliableto develop the habit of always explicitly specifying a scalar reverse when that's what you want.



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net