The pattern matching process is shown using the match operator, "=~", as well as the no match approach using "!~". In the second match process, a "regular expression" is used to set up a pattern. In general, the user is searching for files that end in the appropriate ".pl" extender. The pattern looks for spaces on both sides, but does not want to include that in the actual "tagged" argument (inside the parentheses). That argument is later referenced as "$1" in after the match is found.
#!/usr/bin/perl -w print "Enter a file name:"; chomp($fname = <STDIN>); # File name is read from standard input (keyboard). # Chomp removes any carriage returns from inputEnter a file name: ex2.pl     or     xxx
print "\nLooking for $fname in the following directory:\n";Looking for ex2.pl in the following directory:
total 31 -rw-r--r-- 1 dhyatt faculty 540 Sep 9 19:02 ex1.out -rwxr-xr-x 1 dhyatt faculty 1883 Sep 9 11:45 ex1.pl -rw-r--r-- 1 dhyatt faculty 0 Sep 11 19:50 ex2.out -rwxr-xr-x 1 dhyatt faculty 1577 Sep 11 19:49 ex2.pl -rw------- 1 dhyatt faculty 24576 Sep 11 19:49 ex2.pl.swp -rwxr-xr-x 1 dhyatt faculty 1904 Sep 8 19:13 hello.pl
### Simple Matches ### # Common "if" approach at end of statement using MATCH operator "=~" print "Found file $fname in directory.\n" if $dir_list =~ $fname;Found file ex2.pl in directory.           ( or no response... )
# Familiar "if-else" construction using NO-MATCH operator "!~" if ($dir_list !~ $fname) { print "Sorry... No $fname in this directory.\n\n"; } else { print "Got a Match!\n\n"; }Got a Match!       or       Sorry... No xxx in this directory.
### Advanced Matching Capabilities ### # Create an Array using the directory listing @dir_array = `ls -l`; print "Here is the directory again:\n"; print @dir_array, "\n";
Here is the directory again: total 31 -rw-r--r-- 1 dhyatt faculty 540 Sep 9 19:02 ex1.out -rwxr-xr-x 1 dhyatt faculty 1883 Sep 9 11:45 ex1.pl -rw-r--r-- 1 dhyatt faculty 0 Sep 11 19:50 ex2.out -rwxr-xr-x 1 dhyatt faculty 1577 Sep 11 19:49 ex2.pl -rw------- 1 dhyatt faculty 24576 Sep 11 19:49 ex2.pl.swp -rwxr-xr-x 1 dhyatt faculty 1904 Sep 8 19:13 hello.pl
print "Here are the perl programs:\n"; $max_lines = $#dir_array; # The "$#" returns highest array index $pattern = '\s+(\w+\.+pl)\s'; #Define a pattern using "regular expressions" # Meaning "\s+" - at least one or more spaces or tabs # "\w+" - at least one or more alpha-numeric characters # "\.+" - a period or dot # "pl" - the proper "pl" extender # "\s" - a trailing space $j=0; for ($i=0; $i <= $max_lines; $i++) # Loop through all lines { if ($dir_array[$i] =~ $pattern) {print $1, "\n"; $perlprogs[$j] = $1; $j++; } }Here are the perl programs:
print "The program names are also stored in an array: "; $, = ", "; print @perlprogs; print "\n";The program names are also stored in an array: ex1.pl, ex2.pl, hello.pl