Extracting Matches

Using patterns in a boolean scalar context, as tests for conditionals or loops, you can find out whether your pattern will match some part of a string. You can only get one of the two answers to that question: yes or no. Although this is useful for validating input, or for collating instances of patterns in a string, it's only half the story. Yes or no are fine answers, but even more useful is the capability to find out exactly what bit of data matched the pattern, and then reuse that data later in the pattern, or to build a list of all the matches that were found.

Whether the thing you match with a pattern is useful or not, of course, depends on the pattern. If your pattern is /abc/, the thing that pattern matches is “abc ...

Get Sams Teach Yourself Perl in 21 Days, Second 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.