MC logo

Patterns I (Answer)

  Practice Problems

  1. $fred = "alpha!beta!gamma";
    $fred =~ s/^.*!//;
    print "$fred\n";
    Prints gamma. The pattern matches the most it can, which is the from the start to the second !.
  2. $fred = "alpha!beta!gamma";
    $fred =~ s/^[^!]*!//;
    print "$fred\n";
    Prints beta!gamma. Here, the pattern cannot match ! except at the end, so it cannot extend past the first !.
  3. $fred = "alpha!beta!gamma";
    $fred =~ s/^[^!]*!$//;
    print "$fred\n";
    Prints alpha!beta!gamma. The pattern does not match at all, so no replacement occurs. The pattern cannot match the string since it must match a ! in the last position, and this particular string will not oblige.
  4. $fred = "/this/that/../../smog/drip/../drop";
    $fred =~ s|[^/]+/\.\./||g;
    print "$fred\n";
    Prints /this/../smog/drop. The pattern matches the substrings that/../ and drip/../. The g qualifier mean "global", but matches are done left to right and cannot overlap. Therefore the second .. in the string cannot match the .. at the end of the pattern, because there are no unused string characters to the left.
  5. $fred = "North South East West";
    $fred =~ s/..[^r]../xxxxx/;
    print "$fred\n";
    Prints NxxxxxSouth East West.

<<Using @ARGV Question Passing Subroutine Arguments>>