Blob


1 #!/usr/bin/perl
3 # Get the rightmost program running (you can get the program from the
4 # Downloads section of http://www.intermediateperl.com/ if you don't want to
5 # type the whole thing yourself). Once you have the example working, modify
6 # the rightmost program, take a hash reference of patterns, and return the
7 # key of the rightmost match. Instead of calling it like:
8 #
9 # my $position = rightmost(
10 # 'There is Mrs. Howell, Ginger, and Gilligan',
11 # @patterns{ sort keys %patterns }
12 # );
13 #
14 # call it like:
15 #
16 # my $key = rightmost(
17 # 'There is Mrs. Howell, Ginger, and Gilligan',
18 # \%patterns
19 # )
21 use v5.24;
22 use warnings;
23 use strict;
24 use utf8;
26 sub rightmost {
27 my( $string, $pattern_ref ) = @_;
29 my $rightmost = -1;
30 my $rightkey;
31 while ( my ($key, $regex) = each %$pattern_ref) {
32 my $position = $string =~ m/$regex/ ? $-[0] : -1;
33 if ($position > $rightmost) {
34 $rightmost = $position;
35 $rightkey = $key;
36 }
37 }
38 return $rightkey;
39 }
41 my %patterns = (
42 Gilligan => qr/(?:Willie )?Gilligan/,
43 'Mary Ann' => qr/Mary Ann/,
44 Ginger => qr/Ginger/,
45 Professor => qr/(?:The )?Professor/,
46 Skipper => qr/Skipper/,
47 'A Howell' => qr/Mrs?. Howell/,
49 );
51 my $key = rightmost(
52 'There is Mrs. Howell, Ginger, and Gilligan',
53 \%patterns
54 );
55 print "$key\n";