4.8.4.1 Two More Anchors for Beginning and End of String

4.8.4.1  Two More Anchors for Beginning and End of String

  Perl provides us with a pair of additional anchors \A and \Z that are similar to ^ and $. For single-line strings, ^ and \A behave exactly the same way. Similarly, for single-line strings, $ and \Z are exactly the same. However, for multi-line
strings, the anchoring properties differ. \A always matches the beginning of the string—single line or multi-line. However, as we have seen already, although usually ^ matches at the beginning of a string, if we use the m modifier, ^ matches at the beginning of every line in a multi-line string. Similarly, \Z always forces matching at the end of a string; whether is is a single line string or multi-line string does not matter. $
usually forces matching at the end of a string. But, if the m match modifier is used, $ forces pattern matching at the end of each embedded line in a multi-line string.

Each of the following picks out only the first friend’s name (i.e., Tommy).

 

@allFriends = ($friends =~ /(\A\w+)/);

@allFriends = ($friends =~ /(\A\w+)/g);

@allFriends = ($friends =~ /(\A\w+)/m);

@allFriends = ($friends =~ /(\A\w+)/gm);

 

Using various modifier combinations does not change where \A anchors, namely the beginning of the string. Similarly, each of the following extracts only the hometown of the last friend.

 

@allHometowns = ($friends =~ /(\w+\Z)/);

@allHometowns = ($friends =~ /(\w+\Z)/g);

@allHometowns = ($friends =~ /(\w+\Z)/m);

@allHometowns = ($friends =~ /(\w+\Z)/gm);