Pattern Matching


1. See if a string only contains letters


if ($string =~ /^[A-Za-z]+$/) {

   print “$string only contains letters.\n”;

} else {

   print “$string contains nonletters.\n”;

}


This example applies the PATTERN ^[A-Za-z]+$ to $string.

      ^ assertion applies the pattern to the first character in $string (p. 264)

      [A-Za-z] is a character class of the letters of the alphabet (p. 258)

      + matches 1 or more characters in $string (p. 263)

      $ assertion applies the pattern to the last character in $string (p. 264)


2. Remove punctuation


while ($line = <text_in>) {

   $line =~ s/["(),;:.!?]/ /g; # Removes all punctuation

}


3. Get two words from a line


while ($line = <text_in>) {

   $line =~ m/(\w+)\s+(\w+)/ ; #match two words divided by spaces

   @words = ($1, $2);                                #$1 and $2 backreference the (\w+) matches

}


4. Split line by spaces (p. 299)


@words = split(/ /, $string );


5. Look behind, look ahead assertions (p. 265)

 

$string =~ s/(?<=i )be/am/;                       #changes ‘be’ to ‘am’ after ‘i ’.


6. Capitalize initial letter in a sentence (p. 267)


$string =~ s/(([.!?] | \A) \s*) ([a-z])/$1\u$3/g;