1.11.1 A Few Shortcuts in Pattern Matching

The program given below shows a few shortcuts we can use in pattern matching. First, if we are pattern matching against the special variable $_, it is not necessary to specify it to the left of the =~ operator. If we do not mention the variable on the left, we do not need to specify the =~ operator too. Next, we do not have to specify the operation as m signifying it is a match operation. We can simply start with the left delimiter /.

Program 1.19

#!/usr/bin/perl
#file scanvowels2.pl

use strict;
my $filename;

print "Please give a file name >> ";
$filename = ;
chomp $filename;
open (IN, $filename);

while (){
    if (/a.*e.*i.*o.*u/i){
        print;
    } 
} 

Finally, in the pattern specification above, we have used a qualifier i after the right-delimiting /. It commands Perl to ignore the case of the matching characters in the pattern. So, the vowels for which we are looking can be upper case or lower case.

We end this section by writing a program that is a generalization of the program given above. The program takes a list of files as command line argument and prints every line that contains the five vowels in order, in every file that is given as a command line argument.

Program 1.20

#!/usr/bin/perl

#Takes a list of files and prints all those lines in
#the files that contain the vowels in order.

while (<>){
      if (/a.*e.*i.*o.*u/i){
          print;
      } 
} 

Here, we have used the empty diamond (<>) inside the conditional of a while loop. As discussed earlier, in such a case, Perl considers every command line argument as a file for input. Each file is considered in the sequence it is given. So, the following call to the program in a Unix environment, assuming it is stored in the file scanvowels.pl,

%scanvowels.pl file1 file2 file3 file4

will scan the four files for lines that contain the five vowels in sequence and print such lines if found. If we are in a Unix environment, we can use some shortcuts in specifying the names of files. For example, if in a Unix environment, we type

%scanvowels.pl *

the program will look for the pattern in every file in the current directory. In Unix, the asterisk (*) is used to refer to all files in a certain directory.

In general, pattern matching in Perl can be quite complex. We will discuss pattern matching in detail in Chapter 4.