#!/usr/bin/perl -w # This program experiments with simple matching operations print "Enter a file name:"; chomp($fname = ); # File name is read from standard input (keyboard). # Chomp removes any carriage returns from input print "\nLooking for $fname in the following directory:\n"; $dir_list = `ls -l`; # run the UNIX Command - assign output to a variable print $dir_list,"\n"; ### Simple Matches ### # Common "if" approach at end of statement using MATCH operator "=~" print "Found file $fname in directory.\n" if $dir_list =~ $fname; # 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"; } ### 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"; 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++; } } print "The program names are also stored in an array: "; $, = ", "; print @perlprogs; print "\n";