The "e" Switch

Contents | Up | Prev | Next

# 7.7.1. The "e" Switch

If an `e` is appended to the end of the substitution command, then the right side is treated as a normal Perl expression, giving you the ability to use operators and functions.

The following example, replaces the first word in the sentence with its length:

    use strict;
    use warnings;

    my $string = shift;

    $string =~ s/^([A-Za-z]+)/length($1)/e;

    print $string, "\n";

And the following example, converts the first word that starts with the letter "S" into uppercase:

    use strict;
    use warnings;

    my $string = shift;

    $string =~ s/([Ss][A-Za-z]*)/'<'.uc($1).'>'/e;

    print $string, "\n";

Contents | Up | Prev | Next