Regular Expressions: Examples 2
 
Tally up mentions of various characters
  • Grouped matches are stored in $1, $2, $3 , etc...
#!perl -w

use strict;

my %counts;

my $file = "rj.txt";
open( IN, "<$file" ) or die "Can't open $file: $!";

while (my $line = <IN>) {
    if ( $line =~ /(Romeo|Juliet|Mercutio|Tybalt|Sparky)/ ) {
        my $character = $1;
        ++$counts{ $character };
        }
    }

for my $character ( sort keys %counts ) {
    print "$character is mentioned ", $counts{$character}, " times.\n";
    }
Juliet is mentioned 60 times.
Mercutio is mentioned 19 times.
Romeo is mentioned 137 times.
Tybalt is mentioned 58 times.
Character counting: Revised
  • Above example isn't entirely accurate.
     
  • If multiple characters are on the same line, only the first counts.
     
  • "Romeo kisses Juliet" would count as Romeo only.
     
  • We'll add the "/g" modifier to our expression to make it loop.
     
  • We'll also have it pull out the various Friars
#!perl -w

use strict;

my %counts;

my $file = "rj.txt";
open( IN, "<$file" ) or die "Can't open $file: $!";

while (my $line = <IN>) {
    while ( $line =~ /(Romeo|Juliet|Mercutio|Tybalt|Friar \w+)/g ) {
        my $character = $1;
        ++$counts{ $character };
        }   # while matching
    }   # while <IN>

for my $character ( sort keys %counts ) {
    print "$character is mentioned ", $counts{$character}, " times.\n";
    }
Friar John is mentioned 5 times.
Friar Laurence is mentioned 11 times.
Juliet is mentioned 65 times.
Mercutio is mentioned 26 times.
Romeo is mentioned 155 times.
Tybalt is mentioned 66 times.
Index
Introduction
What Is Perl?
Perl Resources
Running a Perl Program
Perl Thinking
Data Types
Scalars
Strings: Single Quoted
Strings: Double Quoted
Scalar operations
Scalar comparisons
Variables
Lists
Using Lists
Control Structures
Hashes
Hash Manipulation
File Handling
Regex Matching
Regex Matching: Ex. 1
Regex Matching: Ex. 2
Regex Replacing
Subroutines
Anonymous subs
References
Structures
Modules
Modules: File::Find
Modules: Internet
Modules: Win32::*
Everything Else
  Next page >>>