Robert's Perl Tutorial

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


An introduction

Or regex for short. These can be a little intimidating. But I'll bet you have already used some regex in your computing life so far. Have you even said "I'll have any Dutch beer ?" That's a regex which will match a Grolsch or Heineken, but not a Budweiser, orange juice or cheese toastie. What about dir *.txt ? That's a regular expression too, listing any files ending in .txt.

Perl's regex often look like this:

$name=~/piper/
   

That is saying "If 'piper' is inside $name, then True."

The regular expression itself is between / / slashes, and the =~ operator assigns the target for the search.

An example is called for. Run this, and answer it with 'the faq'. Then try 'my tealeaves' and see what happens.

print "What do you read before joining any Perl discussion ? ";
chomp ($_=<STDIN>);

print "Your answer was : $_\n";

if ($_=~/the faq/) {
        print "Right !  Join up !\n";
} else {
        print "Begone, vile creature !\n";
}

So here $_ is searched for 'the faq'. Guess what we don't need ! The =~ . This works just as well:

if (/the faq/) {

because if you don't specify a variable, then perl searches $_ by default. In this particular case, it would be better to use

if ($_ eq "the faq") { 

as we are testing for exact matches.