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 J. Answers to Chapter 10 Exercises

Answer 10.1: Use the line-input operator to get lines. Before you output the line, check if it has the word “ruby” or “python” by trying to match either of those words with a regular expression. If your regular expression succeeds, stop the loop iteration and move on to the next line. If the regular expression fails, continue with the iteration and execute the print statement, which without an argument outputs the value of $_. This is a common Perl idiom for processing lines of files: read in a line and decide if you want to process it, and if not, use next to move on to the next line:

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

while( <> ) {
    next if m/ruby|python/;
    print;
 }

Answer 10.2: Read lines of input, and for each line use the auto-increment operator to add one to the value of $sum. After you do that, check if the word “perl” is in the line, and if it is, use the last command to stop the while loop and move on with the program.

Once you break out of the while loop, the value in $sum is the number of lines of input you read until you found the word “perl”:

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

my $sum = 0;
while( <> ) {
    $sum++;
    last if m/perl/;
    }

say "There were $sum lines until I found perl";

There’s another way that you can do this because Perl automatically tracks the line number for you in the $. special variable:

#!/usr/bin/perl use strict; use warnings; use 5.010; while( <> ) { last if m/perl/; } say "There were $, lines ...

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