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 Q. Answers to Chapter 17 Exercises

Answer 17.1: To repeatedly ask the user for input, wrap my program in a naked block and use redo to start another go-around when you finish one round. To break out of the block, you end input with Control D (or Control Z on Windows), in which case $string gets undef and triggers the last function to end the loop.

There are a couple of ways you could handle the possible error from the user input, and in this answer you’ll use an eval {} block (Answer 17.2 is the same problem with a different method). The eval will catch the error from an invalid regular expression. You need a semicolon after the eval {} block because this is a statement, not a control structure like foreach. After the eval block, output an error message if there is something in the eval error variable $@:

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

{
print 'Enter a string: ';
chomp( my $string = <STDIN> );
last unless defined $string;

print 'Enter a regex: ';
chomp( my $regex = <STDIN> );

eval {
    if( $string =~ /$regex/ ) {
         say 'The string matches!';
         }
    else {
         say 'The string does not match.';
         }
    };
say "Could not use regular expression: $@" if $@;

redo;
}

Answer 17.2: This answer is almost the same as the one for Answer 17.1, but you have to install this module on your own since it doesn’t come with Perl.

You wrap the problematic code in a try block. Instead of checking the result by examining the $@ variable, you put a catch block right after the try. Notice that there ...

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