4/10/2018 - 1:53 PM

Automatic Match Variables

These are how strings are stored when processed by a pattern.

# The part of the string that matches the pattern is automatically stored in $&

if ("Hello there, neighbor" =~ /\s(\w+),/) {
  print "That actually matched '$&'.\n";

# In the above example, the part that matched was " there," (a space, a word, and a comma).
# In comparison, capture $1 would have just the five-letter word.
# Whereas, $& has the entire matched section.

# Whatever came before the matched section is stored in $`. (what the engine skipped over the find the match)
# Whatever came after is stored in $'. (the remainder of the string after the match)
# Note: the regular expression engine searches from left to right. 

# In practise, these automatic match variables can cause some performance issues in larger programs, so most Perl programmers use workarounds.
# A good one if using v5.10 or later, is the /p modifier.