More About Building Patterns

We started this lesson with a basic overview of how to use patterns in your Perl scripts using an if test and the =~ operator—or, if you're searching in $_, you can leave off the =~ part altogether. Now that you know something of constructing patterns with regular expression syntax, let's return to Perl, and look at some different ways of using patterns in your Perl scripts, including interpolating variables into patterns and using patterns in loops.

Patterns and Variables

In all the examples so far, we've used patterns as hard-coded sets of characters in the test of a Perl script. But what if you want to match different things based on some sort of input? How do you change the search pattern on the fly?

Easy. Patterns, like quotes, can contain variables, and the value of the variable is substituted into the pattern:

$pattern = "^d{3} $";
if (/$pattern/) { ...

The variable in question can contain a string with any kind of pattern, including meta characters. You can use this technique to combine patterns in different ways, or to search for patterns based on input. For example, here's a simple script that prompts you for both a pattern and some data to search, and then returns true or false if there's a match:

#!/usr/bin/perl -w

print 'Enter the pattern: ';
chomp($pat = <STDIN>);

print 'Enter the string: ';
chomp($in = <STDIN>);

if ($in =~ /$pat/) { print "true
"; }
else { print "false
"; }

You might find this script (or one like it) useful yourself, as you learn more about regular expressions.

Patterns and Loops

One way of using patterns in Perl scripts is to use them as tests, as we have up to this point. In this context (a scalar boolean context), they evaluate to true or false based on whether the pattern matches the data. Another way to use a pattern is as the test in a loop, with the /g option at the end of the pattern, like this:

while (/pattern/g) {
  # loop
}

The /g option is used to match all the patterns in the given string (here, $_, but you can use the =~ operator to match somewhere else). In an if test, the /g option won't matter, case the test will return true at the first match it finds. In the case of while (or a for loop), however, the /g will cause the test to return true each time the pattern occurs in the string—and the statements in the block will execute that number of times as well.

Note

We're still talking about using patterns in a scalar context, here; the /g just causes interesting things to happen in loops. We'll get to using patterns in list context tomorrow.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset