Endings: The \z, \Z, and $ Assertions
The \z metasymbol matches at the end of the string, no matter what’s inside.
\Z matches right before the newline
at the end of the string if there is a newline, or at the end if there
isn’t. The $ metacharacter usually
means the same as \Z. However, if the
/m modifier was specified and the
string has embedded newlines, then $
can also match anywhere inside the string right in front of a
newline:
/bot\z/ # Matches "robot" /bot\Z/ # Matches "robot" and "abbot\n" /bot$/ # Matches "robot" and "abbot\n" /bot$/m # Matches "robot" and "abbot\n" and "robot\nrules" /^robot$/ # Matches "robot" and "robot\n" /^robot$/m # Matches "robot" and "robot\n" and "this\nrobot\n" /\Arobot\Z/ # Matches "robot" and "robot\n" /\Arobot\z/ # Matches only "robot" — but why didn’t you use eq?
As with ^, the /m modifier lets $ match many times in the same string when
used with /g. (These examples assume
that you’ve read a multiline record into $_, perhaps by setting $/ to ""
before reading.)
s/\s*$//gm; # Trim trailing whitespace on each line in paragraph
while (/^([^:]+):\s*(.*)/gm ) { # get mail header
$headers{$1} = $2;
}In Variable Interpolation, later in this chapter, we’ll
discuss how you can interpolate variables into patterns: if $foo is “bc”, then /a$foo/ is equivalent to /abc/. Here, the $ does not match the end of the string. For a
$ to match the end of the string, it must be at the end of the pattern or be immediately followed by a vertical bar or closing parenthesis. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access