Extracting Matched String from Regexps



next up previous
Next: Flow Control Up: Regular Expressions Previous: Matching Regular Expressions

Extracting Matched String from Regexps

As in vi, grep, and sed, Perl can return substrings which are matched in a regular expression. For instance, here is some Perl code to (sort of) emulate the UNIX basename command:

$file = "/auto/home/pat/c/utmpdmp.c";
($base) = ($file =~ m|.*/([^/]+)$|);

The result of this code fragment is that $base has the value "utmpdmp.c". The parens in the regexp indicate the substring we want to extract.

The return value of a regular expression match depends on context. In an array context, the expression returns an array of strings which are the matched substrings. In a scalar context, typically in a test to see whether or not a string matches a regexp, the expression returns a 0 or 1.

Here is an example of a scalar context. The <STDIN> construct, discussed in detail later, reads in one line of standard input.

$response = <STDIN>;
if ($response =~ /^\s*y/i)
{ print "you said yes\n"; }

Note that the distinction between an ``array context'' and a ``scalar context'' is important in Perl. Many routines and syntactic structures return different types of values depending on context. We will say more about array contexts later.