O'Reilly logo

Learning Perl Student Workbook, 2nd Edition by brian d foy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix G. Answers to Chapter 7 Exercises

Answer 7.1: The regular expression portion of this answer is a simple alternation. You want to match a string that contains either “fred” or “barney”. Use alternation for that. This regular expression matches either word anywhere in the input string:

m/fred|barney/

Once you have matched the string, you can use the Perl special variables $` (that’s a backtick) and $' (that’s a single tick) to get the parts of the string before and after the parts that matched.

Around that, wrap a while loop to prompt the user for a string then try to match the string. Put the m// in the if condition. If the string matches, output the report for the problem. If the string does not match, output a different string:

#!/usr/bin/perl
use strict;
use warnings;

print "Enter a string>> ";
chomp( $_ = <STDIN> );

if( m/fred|barney/ ) {
    print "Before: $`\nName:  $&\nAfter: $'\n";
    }
else {
    print "The string did not match\n";
    }

Here are some sample runs of the program:

$ perl ex7.1.pl
Enter a string>> fred
Before:
Name:  fred
After:

$ perl ex7.1.pl
Enter a string>> barney
Before:
Name:  barney
After:

$ perl ex7.1.pl
Enter a string>> aaaafredzzzz
Before: aaaa
Name:  fred
After: zzzz

$ perl ex7.1.pl
Enter a string>> xxxxbarney
Before: xxxx
Name:  barney
After:

If you write real programs using $`, $', or $&, other Perlers are likely to complain since those variables come with a performance problem as they slow down every match in your program. Perl 5.10 introduces a workaround for ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required