Pattern Matching Exercises

  1. Write a program which asks the user for a filename, then modifies that file, replacing each tab (\t) character with 3 spaces. (solution)
  2. Write a program which reads in lines of text and for each one prints "Weekend!" if the line contains "Saturday" or "Sunday", and for the other days of the week prints "This is a workday." Ignore capitalization in your regular expression. (solution)
  3. Write a program which reads in lines of text and for each line does the following: find the "words" (sequences of non-whitespace characters) and print each one on a line by itself. (solution)

Replies are listed 'Best First'.
Pattern Matching #1
by vroom (His Eminence) on Nov 27, 1999 at 22:04 UTC
    # this programs prompts a user for a filename and then # replaces all tabs in that file with 3 spaces. print "\nWhat file do you want to 'detabify'? "; my $file = <>; chomp $file; # set the input record separator so that <> reads the entire file at o +nce local $/ = undef; open FILE, "< $file" or die "error reading $file - $!"; my $text = <FILE>; # the entire file contents close FILE; $text =~ s/\t/ /g; # replace each tab with three spaces open FILE, "> $file" or die "error writing $file - $!"; print $text; close FILE;
Pattern Matching #2
by vroom (His Eminence) on Nov 27, 1999 at 22:16 UTC
    # chooses a message to print based on the day of the week entered. while ( <> ) { if ( /Saturday|Sunday/i ) { print "Weekend!\n"; } elsif ( /Monday|Tuesday|Wednesday|Thursday|Friday/i ) { print "This is a workday.\n"; } }
Pattern Matching #3
by vroom (His Eminence) on Nov 27, 1999 at 22:31 UTC