Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


Returning the Match

Now things get interesting. What if we want pull something out of a string ? So far all we have done is test for truth, that is say yea or nay if a string matches, but not return what we found. Run this:

$_='My email address is <Robert@NetCat.co.uk>.';

/(<robert\@netcat.co.uk>)/i;

print "Found it ! $1\n";

Firstly, note the single quotes when $_ is assigned. If there were double quotes, we'd need \@ instead of @ . Remember, double quotes "" allow variable interpolation, so Perl looks for an array called @NetCat which does not exist.

Secondly, look at the parens around the entire regex. If you use parens, a side effect is that the first match is put into a variable called $1 . We'll get to the main effect later. The second match goes into $2 and so on. Also note that the \@ has been escaped, so perl doesn't think it is an array. Remember \ either escapes a special character, or gives a special meaning. Think of it as Superman's telephone box. Imagine Clark Kent walking around with his magic partner Back Slash.

Notice how we specify in the regex case-insensitivity with /i and the regex returns the case-sensitive string - that is, exactly what it found.

Try the regex without parens. Then try this one:

/<(robert)\@netcat.co.uk>/i;

You can put the parens anywhere. More or less. Now, run this :

$_='My email address is <Robert@NetCat.co.uk>.';

/<(robert)\@(netcat.co.uk)>/i;

print "Found it ! $1 at $2\n";

See, you can have more than one ! Look at the above regex. Looks easy now, don't you think ? What about five minutes ago ? It would have looked like a typing mistake ! Well, there are some hairier regex to come, but you'll have a good barber.