Section 8.3.  Reversing Scalars

Table of Contents

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.

    Table of Contents
    © 2000- NIV