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 N. Answers to Chapter 14 Exercises

Answer 14.1: Start the program by printing a short message reminding you to enter some lines of input. If you don’t give the program any command-line arguments, the line input operator <> will wait for standard input, so you don’t stare at the terminal waiting for something to happen as your program is staring at you waiting for you to type.

Use index on each line to look for the string “perl”. If the line doesn’t have it, index returns -1 (0 means it was the first character). Assign the value to $pos then check if its value was not -1, meaning you found “perl”. If you found “perl”, output a message that shows its position. If index returned -1, simply output a string that says you didn’t find it:

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

print "Enter some strings, and use Control-D to stop input\n";

while( <> ) {
    my $pos = index $_, 'perl';

    if( $pos != -1 ) {
         say qq(\tI found 'perl' at position $pos);
         }
    else {
         say qq(\tI didn't find 'perl');
         }
    }

Here’s some sample output:

$ perl ex14.1.pl
Enter some strings, and use Control-D to stop input
This is a line without perl
    I didn't find 'perl'
This is a line with perl
    I found 'perl' at position 20
perl is at the beginning
    I found 'perl' at position 0

Answer 14.2: This answer is the same as your program in the Answer to Exercise 14.1 with only a change in one line. Instead of index, use rindex, and instead of “perl”, look for “e”. The rindex function starts looking for the string on the ...

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