Anchors

By default, if a pattern doesn’t match at the start of the string, it can “float” on down the string trying to match somewhere else. But a number of anchors may be used to hold the pattern at a particular point in a string.

The caret[192] anchor (^) marks the beginning of the string, and the dollar sign ($) marks the end.[193] So, the pattern /^fred/ will match fred only at the start of the string; it wouldn’t match manfred mann. And /rock$/ will match rock only at the end of the string; it wouldn’t match knute rockne.

Sometimes, you’ll want to use both of these anchors to ensure that the pattern matches an entire string. A common example is /^\s*$/, which matches a blank line. But this “blank” line may include some whitespace characters, like tabs and spaces, which are invisible. Any line that matches this pattern looks like any other one on paper, so this pattern treats all blank lines equally. Without the anchors, it would match nonblank lines as well.

Word Anchors

Anchors aren’t just at the ends of the string. The word-boundary anchor, \b, matches at either end of a word.[194] So you can use /\bfred\b/ to match the word fred but not frederick, alfred, or manfred mann. This is similar to the feature often called “match whole words only” in a word processor’s search command.

Alas, these aren’t words as you and I are likely to think of them; they’re those \w-type words made up of ordinary letters, digits, and underscores. The \b anchor matches at the start or end of a group ...

Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.