This time, Perl 101 visits some of Perl's more useful in-builtfunctions, and teaches you the basics of pattern matching and substitution.Also included is a list of common string and math functions, together withexamples of how to use them.
One of Perl's most powerful features is the ability to do weird and wonderful things with "regular expressions". To the uninitiated, regular expressions, or "regex", are patterns which are built using a set of special characters; these patterns can then be compared with text in a file, or data entered into a Web form. A pattern match can trigger some kind of action...or not, as the case may be.
Though regular expressions can get a little confusing when you're first starting out with them, a little patience will reap rich rewards, as they can save you a tremendous amount of work. Our very first example illustrates a simple pattern-matching operation, and introduces you to Perl's match operator:
#!/usr/bin/perl
# get a line of input
print "Gimme a line!\n";
$line = ;
chomp ($line);
# get a search term
print "Gimme the string to match!\n";
$term = ;
chomp ($term);
# check for match
if ($line =~ /$term/)
{
print "Match found!\n";
}
else
{
print "No match found\n";
}
A quick explanation is in order here. In Perl, the "pattern" is the sequence of characters to be matched - this pattern is usually enclosed within a pair of slashes. For example,
/xyz/ represents the pattern "xyz".
The example above asks for a line of text and a search term - this search pattern is then used with the match operator =~ to test for a match. The result of the =~ operation is true if the pattern is found in the string, and false if not.
Here's the output of the example above:
Gimme a line!
I'll be back
Gimme the string to match!
b
Match found!
Perl also has the !~ operator, which does the reverse of the =~ operator - it returns true if a match is NOT found.
This article copyright Melonfire 2000. All rights reserved.