DavidSzczesniak
12/4/2017 - 2:29 PM

Remembering Matched Values

Perl lets us store up to 9 expressions in variables $1 through $9. Here are some examples of how this can be used to shorten code, following TIMTOWTDI.


# ==Replace "boys" with "boyz" and "girls" with "girlz"==

# Look for every instance of "boy" or "girl", followed by an "s".
s/(boy|girl)s/$1z/; # with a "z" substituted for the "s"
# the $1 is the first expression used, (boy|girl)

# Example of remembering two matches 
# From: dogs/cats are invited/welcome To: dogs/cats are not welcome/invited
s/(dog|cat)s are (invited|welcome)/$1s are not $2/; # $1 = (dog|cat) and $2 = (invited|welcome)