exercise solutions978-1-4302-0665... · 2017. 8. 29. · appendix exercise solutions this appendix...

45
APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu- tion is an answer, not the answer. Remember that in Perl, there is more than one way to do it, and that applies to these solutions as well. Chapter 1 1. #!/usr/bin/perl -w # chap01ex1. pl print "Hi Mom.\nThis is my second program.\n"; Chapter 2 1. #!/usr/bin/perl -w # chapo2ex1.pl use strict; print "Currency converter\n\n"; print "Please enter the exchange rate: "; chomp(my $yen= <STDIN>); print "Enter first price to convert: "; chomp(my $price1 = <STDIN>); print "Enter second price to convert: "; chomp(my $price2 = <STDIN>); 385

Upload: others

Post on 13-Aug-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

APPENDIX

Exercise Solutions

This appendix contains the answers to the chapter exercises. An important note: each solu­tion is an answer, not the answer. Remember that in Perl, there is more than one way to do it, and that applies to these solutions as well.

Chapter 1 1.

#!/usr/bin/perl -w # chap01ex1. pl

print "Hi Mom.\nThis is my second program.\n";

Chapter 2 1.

#!/usr/bin/perl -w # chapo2ex1.pl

use strict;

print "Currency converter\n\n";

print "Please enter the exchange rate: "; chomp(my $yen= <STDIN>);

print "Enter first price to convert: "; chomp(my $price1 = <STDIN>);

print "Enter second price to convert: "; chomp(my $price2 = <STDIN>);

385

Page 2: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

386 APPENDIX EXERCISE SOLUTIONS

print "Enter third price to convert: "; chomp(my $price3 = <STDIN>);

print "$price1 Yen is ", ($price11$yen), " dollars\n"; print "$price2 Yen is ", ($price21$yen), " dollars\n"; print "$price3 Yen is ", ($price31$yen), " dollars\n";

2.

#!lusrlbinlperl -w # chap02ex2.pl

use strict;

print "enter a hex number: "; chomp(my $hexnum = <STDIN>); print "converted to an int: ", hex($hexnum), "\n";

print "enter an octal number: "; chomp(my $octal = <STDIN>); print "converted to an int: ", oct($octal), "\n";

3.

#!lusrlbinlperl -w # chap02ex3.pl

use strict;

print "enter a value less than 256: "; chomp(my $bin = <STDIN>);

print((128 & $bin) I 128); print((64 & $bin) I 64); print((32 & $bin) I 32); print((16 & $bin) I 16); print((8 & $bin) I 8); print((4 & $bin) I 4); print((2 & $bin) I 2); print((1 & $bin) I 1);

print "\n";

Page 3: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

4.

2 + (6 I 4) - (3 * 5) + 1 ~ -10.5 17 + ((-3 ** 3) I 2) = -3.5 26 + (3 A (4 * 2)) : 37 ((4 + 3) >= 7) II (2 && ((4 * 2) < 4)) = 1

Chapter 3 1.

#!lusrlbinlperl -w # chap03ex1. pl

use strict;

my $target = 12; print "Guess my numberl\n"; print "Enter your guess: ";

my $guess; while ($guess = <STDIN>) {

if ($target == $guess) {

}

2.

print "That's it! You guessed correctlyl\n"; last;

} elsif ($guess > $target) { print "Your number is more than my number\n";

} elsif ($guess < $target) { print "Your number is less than my number\n";

} print "Enter your guess: ";

#llusrlbinlperl -w # chap03ex2.pl

use strict;

for (my $i = 1; $i <= 10; $i++) { print "$i square is: ", $i*$i, "\n";

}

APPENDIX • EXERCISE SOLUTIONS 387

Page 4: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

388 APPENDIX EXERCISE SOLUTIONS

3.

#!/usr/bin/perl -w # chap03ex3.pl

use strict;

for (my $i = 1; $i <= so; $i++) { if ($i % s == o) {

print "$i is evenly divisible by 5\n"; }

}

Chapter 4 1.

#!/usr/bin/perl -w # chap04exl.pl

use strict;

my @a = (2, 4, 6, 8);

foreach (@a) { print "$_ ** 2 = ", $_ ** 2, "\n";

}

foreach (reverse @a) { print "$_ ** 2 = "

}

3.

$ ** 2 "\n"· - , ,

Here is a program that illustrates the answer to this question.

#!/usr/bin/perl -w # chap04ex3.pl

use strict;

my @a = ( 'a a' • . ' bb' ) ; print "first array:\n"; print "@a\n";

Page 5: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

@a = (' ao' • • ' bg' ) ; print "------------\n"; print "second array:\n"; print "@a\n";

Chapter 5 1.

#!/usr/bin/perl -w # chap05ex1.pl

use strict;

my %hash = (

);

scalar => 'dollar sign', array => 'at sign', hash => 'percent sign'

foreach (sort keys %hash) { print "$_: $hash{$_}\n";

}

2.

#!/usr/bin/perl -w # chap05ex2.pl

use strict;

my %phonenumbers =

);

John => '555-1212', Sue => '555-2222', Larry=> '555-3232', Moe => '555-4242'

print "enter name: "; while (<STDIN>) {

chomp; if (exists $phonenumbers{$ }) {

APPENDIX EXERCISE SOLUTIONS 389

print "$_has the phone number: $phonenumbers{$_}\n";

Page 6: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

390 APPENDIX EXERCISE SOLUTIONS

} else { print "$_is not in the phone book\n";

} print "enter name: ";

}

3.

#!/usr/bin/perl -w # chaposex3.pl

use strict;

my %jokes =

);

Java =>"None. Change it once, and it's the same everywhere.", Python => "One. He just stands below the socket and the world " •

"revolves around him.", Perl => "A million. One to change it, the rest to try and do it in "

"fewer lines.", C =>'"CHANGE?!!"'

print "enter programming language: "; while (<STDIN>) {

}

chomp; if (exists $jokes{$_}) {

print "How many $_ programmers does it take to change a lightbulb?\n•; sleep 2; print $jokes{$_}, "\n";

} else { print "That language is not funny .•• \n";

} print "enter programming language: ";

Chapter 6 1.

#!/usr/bin/perl -w # chapo6exl.pl

use strict;

print "enter a number: "; chomp(my $input_num = <STDIN>);

Page 7: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

if {$input_num < o) { print "please enter a positive numberl\n";

} else {

}

my $result = factorial{$input_num); print "$input_num! = $result\n";

sub factorial {

}

my $num = shift;

if {$num == o) { return 1;

} else {

}

my $answer = 1; foreach (2 •• $num) {

$answer = $answer * $_; } return $answer;

# here is the solution using recursion -# a recursive function is a function that calls # itself sub factorial_recursive {

my $num = shift;

}

2.

if {$num == o) { return 1;

} else { return $num * factorial_recursive{$num - 1);

}

#!/usr/bin/perl -w # chap06ex2.pl

use strict;

my $number_of_seconds;

prompt_user();

APPENDIX EXERCISE SOLUTIONS 391

my ($hours, $minutes, $seconds) = secs2hms($number_of_seconds);

Page 8: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

392 APPENDIX EXERCISE SOLUTIONS

print "$number_of_seconds seconds is $hours hours, $minutes " "minutes and $seconds seconds";

print "\n";

sub prompt_user {

}

print "please enter the number of seconds: "; chomp($number_of_seconds = <STDIN>);

sub secs2hms { my ($h,$m);

}

my $seconds = shift;; # defaults to shifting @_ $h = int($seconds/(6o*6o)); $seconds %= 60*60; $m = int($seconds/6o); $seconds %= 60; ($h,$m,$seconds);

Chapter 7 1. Match "hello" followed by zero or more and any character but \n followed by "world"; or, in other words, any string that contains "hello" followed later by "world".

Match one or more digits at the beginning of the string followed by one whitespace char­acter followed by zero or more word characters followed by the end of the string.

Match an uppercase letter at the beginning of a word followed by zero or more lowercase letters to the end of a word; or, in other words, match a word that begins with an uppercase letter followed by any number of lowercase letters.

Match a character, remember it in \1, followed by any number of any characters but \n, followed by the character remembered. In other words, match any string with two occur­rences of the same character.

2.

/"\d.* \d$/

/"[\s\w]+$1

/"\5*$/

3.

#!/usr/bin/perl -w # chap07ex3.pl

Page 9: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

while ( <>) { print if /[aeiouy][aeiouy]/i;

}

4.

#!/usr/bin/perl -w # chap07ex4.pl

while (<>) {

APPENDIX EXERCISE SOLUTIONS 383

print if fA[Aaeiouy]*[aeiouy][Aaeiouy]*[aeiouy][Aaeiouy]*$/i; }

Chapter 8 1.

#!/usr/bin/perl -w # chapo8ex1.pl

use strict;

open(INFH, '<', 'gettysburg. txt') or die $1; open(OUTFH, '>', 'exlout.txt') or die $1;

while (<INFH>) { next if fA\s*$1;

my @words = split; print OUTFH "$_\n" foreach @words;

}

close INFH; close OUTFH;

2.

#!/usr/bin/perl -w # chapo8ex2.pl

use strict;

unless (@ARGV) { @ARGV = qw(filel.dat file2.dat file3.dat);

}

print <>;

Page 10: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

394 APPENDIX EXERCISE SOLUTIONS

3.

#!/usr/bin/perl -w # chapo8ex3.pl

use strict;

my $target; while (1) {

print "What file should I write to? "; $target = <STDIN>; chomp $target; if (-d $target) {

print "No, $target is a directory.\n"; next;

} if (-e $target) {

print "File already exists. What should I do?\n"; print "(Enter 'r' to write to a different name, "; print "'o' to overwrite or\n"; print "'b' to back up to $target.old)\n"; my $choice = <STDIN>; chomp $choice; if ($choice eq "r") {

next; } elsif ($choice eq "o") {

unless (-o $target) { print "Can't overwrite $target, it's not yours.\n"; next;

} unless (-w $target) {

}

print "Can't overwrite $target: $!\n"; next;

} elsif ($choice eq "b") { if (-e "$target.old") {

}

print "Backup $target.old exists. Overwrite it? [yin] "; my $choice = <STDIN>; chomp $choice; if ($choice ne 'y') {

next; }

if ( rename($target, $target.".old") ) { print "OK, moved $target to $target.old\n";

Page 11: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

} else { print "Couldn't rename file: $ !\n"; next;

} } else {

print "I didn't understand that answer.\n"; next;

} } last if open(OUTPUT, '>', $target); print "I couldn't write to $target: $ !\n"; # and round we go again.

}

print OUTPUT "Congratulations.\n"; print "Wrote to file $target\n";

close OUTPUT;

Chapter 9 1.

#!/usr/bin/perl -w # chap09ex1. pl

use strict;

open(FH, '<', 'exl.dat') or die$!;

while (<FH>) { my $name = substr $_, o, 24;

my $address = substr $_, 25, 18; my $city = substr $_, 52, 20;

my $state = substr $_, 72, 2' ' my $zip = substr $_, 75, 5;

print <<EOT;

Record: name $name address $address city $city

APPENDIX EXERCISE SOLUTIONS 395

Page 12: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

396 APPENDIX EXERCISE SOLUTIONS

state $state zip $zip EOT

}

close FH;

2.

#!/usr/bin/perl -w # chap09ex2.pl

use strict;

while (<>) { tr/a-zA-Z/n-za-mN-ZA-M/; print;

}

Chapter 10 1.

#!/usr/bin/perl -w # chaplOexl.pl

use strict;

my $dir =shift II ''; my $size= shift I I '';

die "usage: ex1.pl <din <size>\n" unless $dir and $size;

chdir $dir or die "can't chdir: $!";

# first, a file glob # this gets hidden files too print "using glob:\n"; foreach (<.* *>) {

if (-f $_and -s _ >= $size) { print 1 1

, $_, 1 1 X (30 - length($_)), }

}

-s "\n"· _, ,

Page 13: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

# now using a directory handle print "\n\nusing directory handle:\n"; opendir DH, I. I or die "opendir failed: $!"; while {$_ = readdir(DH)) {

if (-f $_and -s _ >= $size) { print I ~,$_,I I x (30- length($_)),

} } closedir DH;

Chapter 11 1.

#1/usr/bin/perl -w # chap11ex1. pl

use strict;

my @chessboard; my @back = qw(R N B Q K N B R); foreach (0 .. 7) {

APPENDIX EXERCISE SOLUTIONS 397

-s "\n" · _, ,

$chessboard[o]->[$J = "W" . $back[$_]; #White Back Row $chessboard[1]->[$J = "WP"; #White Pawns $chessboard[6]->[$J = "BP"; #Black Pawns $chessboard[7]->[$_] = "B" . $back[$_]; # Black Back Row

}

while (1) { # Print board foreach my $i (reverse (0 .. 7)) {#Row

}

foreach my $j (0 •. 7) { #Column

}

if (defined $chessboard[$i]->[$j]) { print $chessboard[$i]->[$j];

} elsif ( ($i % 2) == {$j % 2) ) { print" .. ";

} else { print " ";

} print " "; # End of cell

print "\n"; # End of row

Page 14: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

398 APPENDIX EXERCISE SOLUTIONS

}

2.

print "\nStarting square [x,y]: "; my $move = <>; last unless ($move=~ fA\s*([1-8]),([1-8])/); my $startx = $1-1; my $starty = $2-1;

unless (defined $chessboard[$starty]->[$startx]) { print "There's nothing on that square !\n"; next;

} print "\nEnding square [x,y]: "; $move = <>; last unless ($move=~ /([1-8]),([1-8])/); my $endx = $1-1; my $endy = $2-1;

# detect if a piece is about to be taken if (defined $chessboard[$endy]->[$endx]) {

}

print "\n$chessboard[$endy]->[$endx] at (", $endx + 1, , , $endy+1, ") is being taken!\n\n";

# Put starting square on ending square. $chessboard[$endy]->[$endx] = $chessboard[$starty]->[$startx]; # Remove from old square undef $chessboard[$starty]->[$startx];

#!/usr/bin/perl -w # chap11ex2.pl

use strict;

my @chessboard; my @back = qw(R N B Q K N B R); foreach (0 .. 7) {

$chessboard[o]->[$_] = "W" . $back[$_]; # White Back Row $chessboard[1]->[$_] = "WP"; # White Pawns $chessboard[6]->[$_] = "BP"; #Black Pawns $chessboard[7]->[$_] = "B" . $back[$_]; # Black Back Row

}

while (1) { # Print board foreach my $i (reverse (0 .. 7)) {#Row

foreach my $j (0 .. 7) { #Column

Page 15: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

}

}

}

if (defined $chessboard[$i]->[$j]) { print $chessboard[$i]->[$j];

} elsif ( ($i % 2) == ($j % 2) ) { print~~ .• ~~;

} else { print II II;

} print II II; # End of cell

print 11 \nll; # End of row

print 11 \nStarting square [x,y]: "; my $move = <>; last unless ($move=- /A\s*([1-8]),([1-8])/); my $startx = $1-1; my $starty = $2-1;

unless (defined $chessboard[$starty]->[$startx]) { print "There's nothing on that square 1\n"; next;

} print "\nEnding square [x,y]: "; $move = <>; last unless ($move=- /([1-8]),([1-8])/); my $endx = $1-1; my $endy = $2-1;

if (defined $chessboard($endy]->[$endx]) { # can't take your own piece

APPENDIX EXERCISE SOLUTIONS -

if (substr($chessboard($endy]->[$endx], 01 1) eq substr($chessboard($starty]->($startx], o, 1)) { print "\nyou can't take your own piecel\n\n"; next;

}

} # can't take a king if ($chessboard[$endy]->[$endx] .~ /K/) {

print "\nyou can't take a kingl\n\n"; next;

}

# Put starting square on ending square. $chessboard[$endy]->[$endx] = $chessboard[$starty]->[$startx]; # Remove from old square undef $chessboard[$starty]->[$startx];

Page 16: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

400 APPENDIX EXERCISE SOLUTIONS

3.

#!/usr/bin/perl -w # chap11ex3.pl

use strict;

my %addressbook;

sub menu { print « EOT;

Please make a choice: 1 add an entry 2 view an entry 3 view all entries 4 delete an entry 5 exit

Your choice: EOT }

sub add_entry {

}

print "Enter name: "; chomp(my $name = <STDIN>); if (exists $addressbook{$name}) {

print "Name alread exists in the address book !\n"; } print "Address: "; chomp(my $address = <STDIN>); print "Phone: "; chomp(my $phone= <STDIN>); $addressbook{$name} = {

};

address => $address, phone => $phone

sub view_entry { print "Enter name to view: "; chomp(my $name = <STDIN>); if (exists $addressbook{$name}) {

print "Address: $addressbook{$name}{address}\n"; print "Phone: $addressbook{$name}{phone}\n\n";

Page 17: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

} else { print "$name is not in address book !\n\n")

} }

sub view_all { foreach my $name (sort keys %addressbook) {

print "Name: $name\n"; print "Address: $addressbook{$name}{address}\n"; print "Phone: $addressbook{$name}{phone}\n\n";

} }

sub delete_entry { print "Enter name to delete: "; chomp(my $name = <STDIN>); if (exists $addressbook{$name}) {

delete $addressbook{$name}; } else {

print "$name is not in address book!\n\n"; }

}

while (1) { menu();

}

chomp(my $answer= <STDIN>); SWITCH: {

}

$answer == 1 and add_entry(), $answer == 2 and view_entry(), $answer == 3 and view_all(), $answer == 4 and delete_entry(), $answer == 5 and exit(o);

Chapter 12 1.

#!/usr/bin/perl -w # chap12ex1. pl

use strict; use Person&;

last SWITCH; last SWITCH; last SWITCH; last SWITCH;

APPENDIX EXERCISE SOLUTIONS 401

Page 18: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

4lrl APPENDIX EXERCISE SOLUTIONS

my $object1 = Person8->new(

);

lastname => "Galilei", firstname => "Galileo", address occupation phone_no

=> => =>

"9.81 Pisa Apts.", "bombadier", "312.555.1212"

my $object2 = Person8->new( last name => "Wall", firstname => "Larry", address => "123 Perl Ave.", occupation => "Programmer", phone_no => "312.555.2323"

);

my $object3 = Person8->new( lastname => "Torvalds", first name => "Linus", address => "593 Linux Ave.", occupation => "Programmer", phone_no => "312.555.3434"

);

print "There are ", Person8->headcount(), •• PersonS objects\n";

foreach my $person (Person8->everyone()) { print "\n", '-' x 80, "\n"; $person->printletter("You owe me money. Please pay it.");

}

Chapter 14 1.

#!/usr/bin/perl -w # chap14ex1.pl

use strict;

use CGI ':standard';

print header(), start_html('Exercise 1');

Page 19: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

if (param) { my $name = param('name') II ''; my $address= param('address') I I ''; my $phone = param('phone') II '';

print h1('Thanks for your information!'),

APPENDIX I EXERCISE SOLUTIONS 403

'Thanks for entering the following information:', br(), $name, br(), $address, br(), $phone;

open FH, '>>', '/tmp/ex1.dat'; print FH ·-· x 80, "\n$name\n$address\n$phone\n"; close FH;

} else {

}

print h1('Please enter some information'), start_ form(), 'Name: ·, textfield(-name => 'name'), br(), • Address: •, textarea(-name => 'address', rows => 3), br(}, 'Phone number: •, textfield(-name => 'phone'}, br(), submit(), end_ form();

print end html(};

2. The solution to this problem is to include the changes shown previously in the section for Chapter 11, exercises 1 and 2.

Page 20: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

404 APPENDIX EXERCISE SOLUTIONS

Chapter 15 1.

#!/usr/bin/perl -w # chap1Sex1. pl

use strict; use DBI;

my($instrument, $musician);

print "Enter instrument: "; chomp($instrument = <STDIN>);

my $dbh = DBI->connect("DBI :mysql :musicians_db", "musicfan'!, "CrimsonKing");

die "connect failed: " . DBI->errstr() unless $dbh;

# use a table join to query the instrument names my $sth = $dbh->prepare("SELECT musicians.name

FROM musicians,what_they_play,instruments WHERE instruments.instrument = ? AND

musicians.player_id = what_they_play.player_id AND what_they_play.inst_id = instruments.inst_id")

or die "prepare failed: " . $dbh->errstr();

$sth->execute($instrument) or die "execute failed: " . $sth->errstr();

# loop through them, printing them while (($musician) = $sth->fetchrow()) {

print " $musician\n"; }

$sth->finish();

$dbh->disconnect();

2.

#!/usr/bin/perl -w # chap15ex2.pl

use strict; use CGI ':standard'; use DBI;

Page 21: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

if (param()) { my $instrument= param('instrument') I I '';

print header(), start_html("Musicians who play $instrument"); hl("Musicians who play $instrument");

APPENDIX EXERCISE SOLUTIONS -

my $dbh = DBI->connect("DBI:mysql:musicians_db", "musicfan", "CrimsonKing") ;

my $sth = $dbh->prepare("SELECT name FROM musicians, what_they_play, instruments WHERE instruments.instrument = ? AND

instruments.inst_id = what_they_play.inst_id AND what_they_play.player_id = musicians.player_id")

or die "prepare failed: " • $dbh->errstr();

$sth->execute($instrument) or die "execute failed: " • $sth->errstr();

my($name);

while (($name) = $sth->fetchrow()) { print "$name plays the $instrument.<br>";

} print

end_html; } else {

print header(), start_html('My Favorite Instrument'), hl('Select an Instrument'}, start_ form(), '<select name="instrument">';

my $dbh = DBI->connect("DBI:mysql:musicians_db", "musicfan", "CrimsonKing");

my $sth = $dbh->prepare("SELECT instrument FROM instruments") or die "prepare failed: " • $dbh->errstr();

$sth->execute() or die "execute failed: " . $sth->errstr();

my($instrument);

while (($instrument) = $sth->fetchrow()) { print qq{<option value="$instrument">$instrument</option>};

}

Page 22: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

406 APPENDIX • EXERCISE SOLUTIONS

}

print '</select>', br(), submit('Show musician(s)'), end_ form(), end_html();

Page 23: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

Index

Symbols ! (not) Boolean operator, 30

operator precedence, 36 !=(not equal to) comparison operator, 28 ! - (negated regex match) operator, 35

operator precedence, 36 patterns not matching, 151

#(comments), 3 documenting programs, 6

#!(hash bang), 3 $ (anchor to end)

escaping metacharacters, 155 $ (scalar variables)

assignment(=) operator, 37 scalars, 37

$prefix naming conventions, 111

$! special variable file error, openO function, 178, 179

$#array array's last index, 95

$array accessing single array elements, 92

$_(special variables), 44 default value, 217

$1 special variable controlling buffering, 193

%prefix naming conventions, 111

& (AND) bitwise operator, 25 && (and) Boolean operator, 29

operator precedence, 36 &sub_routine

declaring subroutines in Perl4, 133 * (asterisk)

escaping metacharacters, 155 repetition with quantifiers, 163

**(exponentiation) operator assignment(**=) operators, 39 operator precedence, 36

+ (plus sign) escaping metacharacters, 155 repetition with quantifiers, 163

-> (infix dereference) arrow operator ${$ref->} arrow notation, 239 matrices, 242 methods, 255 operator precedence, 36 references in references, 239

. (period) escaping metacharacters, 155 pattern matching at end of string, 156

I (forward slash) character regular expressions, 151

0 (zero) definitions of false, 27

=(equals) assignment operator $(scalar variables), 37

==(equals equals) comparison operator, 27 not assignment operator(=), 37 numeric comparison operators, 54

=- (regex match) operator, 35 counting character occurrences, 210 finding patterns, 151 operator precedence, 36 translating a string, 210

=> (list separator) operator, 35 creating hashes, 112 dynamic CGI program, 335 named parameters, 146 operator precedence, 36

? (question mark) escaping metacharacters, 155 repetition with quantifiers, 162

::(colons) translating into directory separators,

288 @ array prefix character

see under arrays [] square brackets

escaping metacharacters, 155 patterns, 158 references to anonymous arrays, 232

modifying referenced array, 238 \ (backslash character)

escape sequences, 17 double quoted string, Wmdows, 178

escaping metacharacters, 155 operators, 35

\ (reference of) operator creating reference for existing variable,

231 operator precedence, 36

11 (anchor), 155 11 (XOR) bitwise operator, 26 II negating character class [], 158 _(underscore)

default filehandle for file tests, 217 407

Page 24: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

-(backquote) character backquotes,225,226

{} curly brackets escaping metacharacters, 155 hashes, 114 references in references

using -> shorthand, 239 references to anonymous arrays

modifying referenced array, 237 references to hashes, 238

anonymous hashes, 232 repetition with quantifiers, 164 statement blocks, 7 subroutines, 128

I (OR) bitwise operator, 26 either-or operator, Regex, 161

I character escaping metacharacters, 155 pipes, 194

II (or) Boolean operator, 30 operator precedence, 36

- (NOT) bitwise operator, 26 operator precedence, 36

<(less-than) comparison operator, 28 < (read mode)

open() function, 180 <=> spaceship comparison operator, 29 « (left shift) operator, 35

operator precedence, 36 <>(diamond)

see diamond(<>) > (greater-than) comparison operator, 28 > (write mode)

open() function, 180 » (append mode)

open() function, 181 » (right shift) operator, 35

operator precedence, 36

A \a (alarm) escape sequence, 8 <a> tags

CGI.pm module generating, 327 a() method

CGI.pm module, 327 providing attributes for, 330

abstraction encapsulation,256,257

accessor methods methods, 271 Person class, 282 shift() function, 272

action= attribute CGI scripts processing form data, 331

addition(+) operator, 22 assignment(+=) operator, 39 operator precedence, 36

address book example, trees, 247 adding another level, 249 deleting data, 249 extracting data, 249 making new entries, 248 printing out data, 248

alarm (\a) escape sequence, 8 alphabetical order

finding character's ASCII value, 33 anchors

common errors writing Regexes, 174 patterns, 155, 156

AND (&) bitwise operator, 25 operator precedence, 36

AND keyword WHERE clause, 361

and (&&) Boolean operator, 29 operator precedence, 36

anonymous arrays accessing referenced array, 234

actual memory location, 235 creating reference to, 232, 234

anonymous data references creating. 230

anonymous hashes creating reference to, 232

anonymous references counting. 242

Apache configuration

troubleshooting CGI scripts, 318 creating CGI directory, 316 errorlogffie

troubleshooting CGI scripts, 318 append mode (»)

open() function, 181 arguments, 21

open() function, 177 parentheses 0 for, 7

arguments, subroutines, 129,141-146 @_array, 133 default values, 145

named parameters providing, 146

named parameters, 145 passing arrays as, 144 passing by reference, 141 passing into subroutines, 133-137 passing lists, 143 stopping functions modifying, 142

$ARGV special variable, 188 arithmetic operators, 22 array functions, 104

pop() function, 105 push() function, 105 reverse() function, 104 shift() function, 107

Page 25: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

sort() function, 108 unshift() function, 107

arrays, 87-109 $#array, 95 $array, 92 @ prefix character, 87

naming conventions, 111 @ARGV array, 186

command line arguments, 186 diamond(<>), 186, 187 displaying array contents, 186 mehandles, writing to rues, 191 my() function, 186 passing arguments into subroutines,

136 push() function, 188 shift() function, 143, 187 storing into variables, 186 use strict statement, 186

@array accessing multiple elements, 97

@EXPORT package variable, 289 @INC array, 262

changing, 263 lib pragma, using, 264 require statement using, 263

@_array passing arguments into subroutines, 133

accessing data in referenced, 239 accessing multiple elements, 97 accessing single elements, 91

using [] to identify, 92 adding elements to, 91 array elements

accessing in anonymous array, 236 array functions, 104 array index, 93 array slice

accessing multiple elements, 97 assigning in scalar context, 90 assigning values, 87, 112, 113 counting occurrences in hash, 123 declaring arrays, 88 double-quoted strings, 89 foreach loop, 68, 99 hashes

assigning values from, 113 assigning values to, 112 compared, 111

lists, 87 looping through, 95

left to right, 97 naming conventions, 87,111 print() function, 89 references to

accessing data in, 240 anonymous arrays, 232

Regexes, common errors writing, 17 4 stacks, 105

ASCII value finding character's ASCII value, 34

assignable lists, 86 assigning values

arrays, 87 hashes, 112 lists, 78

assignment (=, +=, ... ) operators $(scalar variables), 37 autodecrement (--)operator, 39 autoincrement (++)operator, 39 multiple assignments, 41 operator precedence, 38

associative arrays see hashes

attributes action= attribute, 331 class attributes, 273 creating classes

naming/ storing attributes, 267 described, 254 get-set methods, 273 providing attributes for classes, 269 providing for CGI.pm methods, 330

a() method, 330 autodecrement ( ··) operator, 39 auto increment ( ++) operator, 39 autovivification

B

automatic creation of references, 243 chessboard example, matrix, 244

\b (word boundaries) pattern matching, 160

\b (backspace) escape sequence, 8 backquotes C) character, 225, 226 backreferences

Regular expressions, 165, 174 backslash character

escape sequences, 17 double quoted string, Wmdows, 178

escaping metacharacters, 155 operators, 35

backspace (\b) escape sequence, 8 bareword warning, 16 base class

see superclass Benchmark module

standard modules, 302 bidirectional pipes

piping in and out of a process, 198 binary numbers, 15

conversion to strings, 20,21 errors using, 16

binary system, 9

409

Page 26: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

410 INDEX

bits, 9 bitwise operators, 24

AND(&) operator, 25 NOT H operator, 26 operator precedence, 36 OR (j) operator, 26 significance of bits, 25 XOR (A) operator, 26

blank line after header troubleshooting CGI scripts, 318

bless() function blessing again, 267 creating classes, 265 syntax, 265

blocks statement blocks, 7

body, subroutines, 130 Boole, George, 27 Boolean logic, 27

if statements, 53 Boolean operators, 29

and(&&) operator, 29 not (!) operator, 30 or @ operator, 30 xor (exclusive or) operator, 30

boundaries, words pattern matching, 160

breaking the loop looping constructs, 71

buffering controlling output, 193 controlling using $1, 193

bugs, lO Bunce, Tim, 365 bundles

c

Bundle::libnet, 312 Bundle::LWP, 31i

documentation, 312 CPAN module helping download, 311 detecting package dependencies, 311

canonpath() function File::Spec module, 301

case sensitivity i for insensitive, 153 MySQL server, 352 pattern matching, 153

catdir() function File::Spec module, 301

catfile() function File::Spec module, 301

CGI (Common Gateway Interface), 315-346 creating CGI directory, 316 generating HTML, 320 processing form data, 330 webserver access, 316

writing CGI programs, 316 exported environment variables, 319 hello world program, 317

CGI scripts, 315 chessprogram,335-344 developing CGI script with DBI,

375-382 dynamic CGI program, 333

example, 334 param() method, 332, 333 start_form() method, 335 textfield() method, 335

environment variables displaying,319,320 exported, 319

generating HTML web page with CGI.pm, 324 without CGI.pm, 322

state, 335 static CGI program, 332 troubleshooting

perlmonks website, 318 why use Perl, 315 writing, 316

blank line after header, 317,318 hello world program, 317 permissions, 317 troubleshooting, 318

CGI.pm module, 322 example using, 326 generating <a> and <p> tags, 327 method types, 329 methods

a() method, 327 calling methods, 328 dynamic CGI program using, 335 generating more than one tag, 329 generating one tag, 330 header() method, 326 invoking, 329 named parameters, 329 pO method, 327 print() function, 328 start_html() method, 326, 329

processing form data, 322 tags, generating, 326

CGI::Carp module chess CGI program, 344

character classes [] negating, 158 patterns, 158 predefined character classes, 159 sequences of characters, 159

characters escaping metacharacters, 155

chdir() directory function, 219 chess CGI program, 335

Page 27: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

chessboard example, matrix, 242 autovivification, 244 making moves, 244, 247 printing checkered effect, 246 setting up board, 244, 246

chmod command, 4 chmod() directory function, 222 chomp() function

passwords, 57 standard input <STDIN>, 47 user/runtime specified patterns, 155 while loop, 66

chop() function standard input <SID IN>, 48

class attributes, 273 Person class, 282

classes attributes, providing for classes, 269 constructors, 268 creating, 264

bless() function, 265 constructors, 268 get -set methods, 273 inheritance, 269 ref() function, 265 storing attributes, 267

described, 255 inheritance, 256 instances, 255 interfaces, 256 methods, 255 methods, creating, 271

class attributes, 273 get-set methods, 273 privatizing methods, 277 utility methods, 279

naming conventions, 256 objects, 255

constructors, 257 destructors, 258

static data, 255 static methods, 255 subclass, 257 superclass, 257

close() FTP method, 261 close() function, 178 Cohen, Max

patterns, 149 columns

see fields comma operator (arguments), 35 command line interface (Cil), MySQL,

352 commands

capturing output using backquotes, 225 flexible use of command line arguments,

298

commands, list of CREATE DATABASE, 353 CREATE TABLE, 353 DELETE, 382 DESCRIBE, 354 GRANT,354 INSERT,355 mysqlshow,·351 REPLACE, 383 SELECT,358 UPDATE,382 USE,353

comments,3 documenting programs, 6

comparison operators, 27 equals(==), 27 greater-than(>), 28 less-than(<), 28 not equal to(!=), 28 operator precedence, 36 spaceship operator ( <=>), 29 string comparisons, 33 true or false, 27

complex data structures using references for, 242

matrices, 242 trees, 247

concatenation (.) operator assignment(.=) operators, 39 operator precedence, 36

concatenation string operator, 31 concurrency

relational databases, 347 conditional operators

if ... else statements, 58 if ... elsif statements, 59 if statements, 52 introduced, 35 logical operators, 58 operator precedence, 36 unless statement, 61

connect() method, DBI module, 366 constants, 13 constructors

class constructors, 257 creating classes, 268 described, 257 Person class, 282

content type CGI scripts generating HTML, 320 troubleshooting CGI scripts, 318

conversions octal, hex and binary; 20 strings and numbers, 20

rules, 33 Conway, Damian

Object Oriented Perl, 253

411

Page 28: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

412 INDEX

counting hashes,122,197

CPAN (Comprehensive Perl Archive Network), 305

accessing CPAN shell, 309 CSPAN confusion, 258 detecting package dependencies, 311 modules, finding to installihg, 308

installing manually, 308 installing with PPM, 307 modules available at, 287

search engine, 306 standard module doesn't exist, 312 using existing modules, 306

CREATE DATABASE command, 353 CREATE TABLE command, 353

curly brackets {} escaping metacharacters, 155 hashes, 114 references in references, 239 references to anonymous arrays, 237 references to hashes, 238, 232 repetition with quantifiers, 164 statement blocks, 7 subroutines, 128

currency conversion program, 46 current directory, 262 cwdO FfP method, 260

D ·d file test, 199 -doption

debugging, 10 /dmodifier

removing spaces in strings, 210 \d (digit 0-9)

predefined character classes, 159 \D (any nondigit)

predefined character classes, 159 data

data patterns, Regexes, 149 data types, 13 extracting from MySQL database, 358 reference count, 241

data structures using references for complex, 242 visual representation of, 295

database commands CREATE DATABASE, 353 CREATE TABLE, 353 DELETE,382 DESCRIBE, 354 GRANT,354 INSERT,355 REPLACE, 383 SELECT, 358

UPDATE,382 USE,353

database handler DBI connectO method, 366

databases creating a database, 352 extracting data from, 358 indexing, 383

Data::Dumper module choosing output variable name, 296 standard modules, 295

DBD (Database Driver) modules DBI (Database Independent) module, 365

DBD::mysql module installing, 365

DBI (Database Independent) module, 347, 365

database handler, 366 DBD (Database Driver) modules, 365 developing CGI script with, 375-382 DSN (data source name), 366 executing SQL query with DBI, 367,369 installing, 365 joins, 374 methods

connectO method, 366 disconnectO method, 367 errstrO method, 367 executeO method, 368 fetchrowO method, 368 finishO method, 368 prepareO method, 368

Perl connecting to MySQL, 366 placeholders, 372 state handler, 368

debugging visual representation of data structures,

296 declaring subroutines, 128, 130 default values

subroutine arguments, 145 definedO function

if statements, 57 definite loops, 63 del command (Wmdows), 220 DELETE command, 382 deleteO FfP method, 260 deleteO hash function, 120

removing elements from hash, 114 delimiters

Regexes changing, 170 choosing your own, 19

dereferencing accessing data in references, 233, 234 assigning values to references, 241 undefcommand,242

Page 29: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

derived class, 257 DESC (descending) qualifier

ORDER BY clause, 362 DESCRIBE command, 354 destroy() method

object destruction, 281 destructors

described, 258 object destruction, 281 references, 276

Devicelnfo() function Win32::Sound module, 304

Devices() function Wm32::Sound module, 304

diamond(<>), 183-189 $ARGV special variable, 188 @ARGV special array, 186, 187 command line arguments, 184 data file on command line, 185 description, 158, 184 file globbing, 215 how it works, 187 no command line arguments, 184 opening and closing file, 185 reading file in list context, 188, 195

array oflast x lines read, 189 reading from <STDIN>, 184 summary, 204 working with trill, 211

die() function chess CGI program, 344 file error, open() function, 178 program errors, 49

die() method, DBI module executing SQL query with DBI, 370

digit (\d) predefined character, 159 non-digit (\D), 159

directives use warnings, 5

directories changing directory, 219

effect on shell, 219 example, 222

character indicating, 218 creating (making), 221

example, 222 current directory, 262 deleting (removing), 222,297 directory handles, 218 directory separators

translating colons (::) into, 288 listing and examining contents, 216

listing example, 222 opening directory, 218 reading directory, 218, 219 setting up, 3

testing if file is a directory, 217 traversing directory trees, 297

directory functions chdir() function, 219 chmod() function, 222 mkdir() function, 221 opendirO function, 218 readdirO function, 218 rmdirO function, 222

disconnect() method, DBI module, 367 division (/) operator, 22

assignment(/=) operators, 39 operator precedence, 36

do .. until loop, 69 do .. whileloop,69 do statement, 261

require statement compared, 262 documentation

documenting programs, 6 online documentation, 290

double-quoted strings, 17 array variables, 89 lists, 79 qq/1, 19 quotes inside quotes, 18 variable processing, 17

downloading packages detecting package dependencies, 311

DSN (data source name) connect() method arguments, 366

debugging, 10

E -e file test, 199 \E (end of pattern)

escaping metacharacters, 156 each() function

hash functions, 119 piping out to a process, 198

editors choosing a text editor, 2

either-or operator Regular expressions, 161

emacs web reference for, 3

empty list, 77 empty strings

definitions offalse, 27,28 encapsulation, 256

class constructors, 257 end of file characters

Unix and Windows, 211 end of pattern (\E), 156 $ENV {HOMEIPATHIUSER}, 213 %ENVhash, 213-215 %ENY, CGI scripts, 319

413

Page 30: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

414 INDEX

environment variables CGI scripts exporting, 319 inherited from shell, 213

equal to (eq) string operator, 34 equals(=) assignment operator

$(scalar variables), 37 equals equals(==) comparison operator, 27

not assignment operator(=), 37 numeric comparison operators, 54

errors bareword warning, 16 chess CGI program, 344 die() function, 49 syntax error, 16 writing into log files, 292

errstr() method, DBI module, 367 executing SQL query with DBI, 368

escape sequences, 8 \a (alarm), 8 \b (backspace), 8 \n (newline), 4, 8 \r (carriage return), 8 \t (tab), 8 \x (Unicode character), 8 backslash character, 17 strings, 17 tab representation, 17

escaping metacharacters, 155 evaluating statements

short -circuited evaluation, 63 exclusive OR (") bitwise operator, 26 exclusive OR (xor) Boolean operator, 30 executability

character indicating executable, 218 file tests (-x) , 199 testing if file is executable, 217

execute() method, DBI module executing SQL query with DB I, 368, 370 using placeholders, 373 using placeholders and joins, 37 4

executing a program programming, 2 system() function, 223

exercise solutions chapter 1, 385 chapter2,385-387 chapter 3, 387-388 chapter 4, 388-388 chapter 5, 389-390 chapter6,390-391 chapter7,392-393 chapter8,393-394 chapter9,395-396 chapter 10, 396 chapter11,397-400 chapter 12, 401

chapter14,402-403 chapter 15, 404

exists() hash function, 120 exit() function, 48

if statements, 61 numeric comparison operators, 55

exponentiation (**) operator, 23 negative numbers, handling, 24 operator precedence, 36

@EXPORT package variables, 289 %EXPORT_TAGS hash, 290 Exporter module, 288

import() subroutine, 289 using in logging module, 293

expression modifiers, 62 foreach loop, 104 looping constructs, 70

F -f file test, 199 \f (form feed)

predefined character classes, 159 false, 27 fetchrow() method, DBI module

executing SQL query with DBI, 368, 370 <FH>

see filehandles fields

creating database table, 353 relational databases, 348 showing all fields, 354

file functions chmod() function, 222 close() function, 178 link() function, 220 open()function,177 readlink() function, 221 rename() function, 203, 220 symlinkO function, 220 unlink() function, 220

file globbing, 215-218 reading from file glob, 215

file slurp reading file in list context, 188, 195

file tests checking status before opening, 199 directory handle, using, 218 executability, 199 file exists (-e), 199

examples, 199,201,202 file glob, using, 216 file name is directory name (-d), 199

example, 201,202 file test operators, 199 ownership (-o), 199

example, 203

Page 31: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

perldoc perlftmc, 199 permissions, 200 plain file (-f), 199 readability (-r), 199

example, 202 size ( -s, -z), 199 unexpected response

example, 201 writability (read-only) (-w), 199, 200

example, 200, 202 filehandle argument, open() function, 177 filehandles, 177-182

closing, 179 default filehandle for file tests, 217 my function, 178 pipes, 194 piping out to a process, 198 print() function, 190 reading file in list context, 188 reading file in scalar context

line by line until EOE 181 printing with line number, 181

reading from a pipe, 195 summary, 204 writing to files, 190 <STDIN> standard input, 177

filename argument, open() function, 177 specifying full path, 178

filenames writing portable programs, 301

files deleting from disk, 220 deleting useless files program, 298 do statement, 261 directory, testing if file is a, 217 executing/running, 3, 4

making executable, 4 testing if executable, 217

file globbing, 215 file tests, 199-203, 217 hard link, creating, 220 ownership

testing if file is owned, 217 printing file size, 217 reading, testing if can be read, 217 renaming, 220

example, 222 require statement, 262 stat of the file, 217 symbolic (soft) link, creating, 220

example, 221 reading, 221

transfer to and from FTP server, 258 use statement, 263 writing to, 190-193

testing if can be written, 217

File::Find module find() method, 297 standard modules, 297 wanted() subroutine, 297

File::Spec module canonpath() function, 301 catdir() function, 301 catfile() function, 301 documentation, 302 path() function, 301 splitdir() function, 301 splitpath() function, 301 standard modules, 301 trnpdir() function, 301

find() method, File::Find module, 297 finish() method, DBI module, 368 finite loops, 63 flags

Getopt::Long module, 300 Getopt::Std module, 298

floating point numbers, 15 flock() function

locking files, 292 flow charts, 51

if statement, 51 loops, 52

for loop, 68 arrays, looping through, 95

foreach loop, 68 arrays, looping through, 97 arrays, processing, 99 expression modifiers, 104 referenced arrays, 235 traversing trees, 250

fork() function, 226 form data

CGI scripts processing, 330 action= attribute, 331 CGI.pm,322 listing parameters, 332 returning parameter value, 332 simple form example, 331

param() method, 332 widgets, 330

form feed (\f) character, 159 Format() function

Wm32::Sound module, 304 forward slash (!) character

regular expressions, 151 FTP methods, 260 FTPservers

transferring files, 258 fullname() method

Person class, 282 utility methods, 280

fully qualified variable names, 139

415

Page 32: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

416 INDEX

functions

G

see also subroutines array functions, 104-109 described, 127 directory functions, 218-222 file functions, 177, 178, 220-222 hash functions, 117-122 invoking,292 list functions, 78, 81 parentheses 0 for arguments, 7 string functions, 206-208 subroutines compared, 128 system() function, 223

I g (global) modifier, Regexes, 171 get methods, 254 get() FfP method, 260 get() method

visiting remote web sites, 311 get-set methods, 273 getopts() method, Getopt::Std module, 299 Getopt::Long module

standard modules, 300 Getopt::Std module

getoptsO method, 299 standard modules, 298

getprintO method visiting remote web sites, 312

getpwent() function, 226 getstore() subroutine

visiting remote web sites, 312 global variables, 41, 137

scope, 137 goto statement

looping constructs, 76 GRANT command, 354 grave character

see backquote (') character greater than (gt) string operator, 34 greater than or equal to (ge) operator, 34 greater-than(>) comparison operator, 28

H hashbang,3 hash functions, 117

delete() function, 120 each() function, 119 exists() function, 120 keys() function, 117 reverse() function, 122 values() function, 118

hash() session method, 260 hashes, 111-125

accessing data in referenced, 240 address book example, trees, 248

arrays compared, 111 assigning values

from an array, 112 to an array, 113

counting, 197 creating classes

providing attributes, 270 curly brackets{}, 114 delete() function, 114 elements

adding,114 changing, 114 checking existence, 120 removing, 114, 120

examples using, 121 counting occurrences in array, 122 creating readable variables, 121 reversing information, 121

functions, 117 hash keys, 112 key/value pairs, 112

listing keys, 117 listing pairs, 119 listing values, 118

list context, 115 list separator(=>) operator, 112 my function, 114 named parameters, 146 naming conventions, 111 phone book comparison, 111 references to anonymous hashes, 232 references to hashes, 238 scalar context, 116 sort order, 111 use strict statement, 114 values, 112

working with, 113 head() method

visiting remote web sites, 312 headcountO method, 273 header() method

CGI.pm module, 326 developing CGI scripts, 379

helloworld.pl, 3 here-documents, 20

generating HTML with CGI.pm, 325 hex() function

conversion to strings, 21 hexadecimal numbers, 15

conversion to strings, 20 errors using, 16

hexadecimal system, 9 recognizing numbers as hex, 10

HTML CGI scripts generating, 320

CGI.pm,322

Page 33: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

with CGI.pm, 324 without CGI.pm, 322

chess CGI program, 345 HTTP header

writing CGI scripts, 317

i for insensitive case sensitivity, patterns, 153

if statements, 52-63 Boolean logic, 53 curly braces around statements, 52 defined() function, 57 developing CGI scripts, 380 exit() function, 61 expression modifiers, 62 flow charts, 51 if ... else statements, 58 if ... elsif statements, 59 logical operators, 58 numeric comparison operators, 54 short-circuited evaluation, 63 string comparison operators, 56 syntax, 52

import() subroutine, 288 module prepared to export, 289

<IN> list context filehandles, writing to files, 191

indefinite loops, 63 file tests example, 202

indentation, 7 index() string function, 206 indexes

array index, 93 databases, 383 indexing into strings, 205

infinite loops, 66 looping constructs, 63

infix dereference (->) operator ${$ref->} arrow notation, 239 matrices, 242 methods, 255 operator precedence, 36 references in references, 239

inheritance, 256 creating classes, 269

init() method private methods, 279

INSERT command, 355 instances of classes, 255 integers, 14

handling large numbers, 14 interfaces, 256 interpolation

user/runtime specified patterns, 154 variable interpolation, 44

interpreter location of interpreter, 3

Unix users, 4 interpreting code

text inside quotes, 4 invoking subroutines, 129 iteration

J

foreach loop processing arrays, 100 modifying iterator value, 101

join() function Regular expressions, 173

joins

K

DBI module using joins, 374 SELECT command, MySQL, 364 selecting without joins, 363

key/value pairs creating readable variables, 121 hashes, 112 piping out to a process, 198

keyboard standard input <STDIN>, 46

keys creating database table, 353 relational databases, 348

keys() hash function, 117 keywords

avoiding use as variable names, 6 kill() function, 226 Kleene, Stephen

Regular expressions, 150

L last keyword

looping constructs, 71 last statement

loop labels, 7 4 leO function, 198 left shift ( «) operator, 35

operator precedence, 36 length() string function, 206 less than (It) string operator, 34 less than or equal to (le) operator, 34 less-than(<) comparison operator, 28 lexical variables/scope

declaring arrays, 88 my function, 41, 140 scope, 137, 140 scoping variables, 41 variables, 41

libpragma @INC array using, 264

libwin32 modules, 304

417

Page 34: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

418

link() file function, 220 links

renaming files, 220 using functions in Unix/Wmdows, 220

list context, 90 capturing output using backquotes, 225

example, 226 hashes, 115 print() function, 116 reading file in, 188 reading from file glob, 215

list functions print() function, 78, 84 reverse() function, 81

list separator(=>) operator, 35 creating hashes, 112 dynamic CGI program, 335 named parameters, 146 operator precedence, 36

lists, 77-87 accessing values, 83, 84

groups of values, 86 multiple values, 85

arrays,87 assignable lists, 86 assigning values, 78 double-quoted strings, 79 empty list, 77 foreach loop, 68 list slices, 85, 87 mixing strings, numbers and variables, 78 parentheses(), 78 passing as arguments, 143 qw II, creating with, 80 ranges, 81,87 single-quoted strings, 80

literal, 13 localhost, 316 localtime() function, 224

CGI scripts generating HTML, 323 locking files

flock() function, 292 log files/levels, 291 logical operators, 58 login() FfP method, 260

which login() to use, 259 looping constructs, 63-76

arrays, looping through, 95 breaking the loop, 71 controlling the loop, 71 definite loops, 63 do .. until loop, 69 do .. while loop, 69 expression modifiers, 70 finite loops, 63 flow charts, 52

for loop, 68 foreach loop, 68 goto statement, 76 indefinite loops, 63

file tests example, 202 infinite loops, 63 last keyword, 71 last statement, 7 4 loop control variable, 69 loop labels, 7 4 next statement, 72 redo statement, 73 reexecuting the loop, 73 until loop, 67 while loop, 63

piping out to a process, 198 lowercase

leO function, 198 Is() FfP method, 260

M lm (multiple lines) modifier, Regexes, 171 Macllroy, Doug

pipes, 194 matchtest.pl

user/runtime specified patterns, 154, 155 matrices

-> syntax, 242 chessboard example, 242

making moves, 244, 247 setting up board, 244, 246

using references, 242 memory

Regular expressions, 165 metacharacters

quantifiers, 162 Regular expressions, 155

common errors writing, 17 4 table summarizing, 164

methods accessor methods, 271 calling methods (->), 255 CGI.pm module, 329 class methods, 255 classes, 255 creating methods for classes, 271

class attributes, 273 get-set methods, 273 privatizing methods, 277 utility methods, 279

described, 254 FfP methods, 260 get methods, 254 get-set methods, 273 invoking, 255 private methods, 277

Page 35: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

same name, different class, 256 set methods, 254 static methods, 255 subroutines, 255 utility methods, 279

mirror() method visiting remote web sites, 312

mkdir command, 3 mkdir() directory function, 221 mode argument, open() function, 177, 178 modifiers

/d (delete), 210 Regexes, 171

modules,287-313 see also packages bundles, 311

Bundle::libnet, 312 Bundle::LWP, 311

CGI.pm module, 322 CPAN module, 308 CPAN repository, 305 creating a non-00 module, 290 Database Independent (DBI) module, 347 DBD::mysql module

installing, 365 detecting package dependencies, 311 Exporter module, 288 finding and downloading, 308 import() subroutine, 288 installing modules using CPAN, 308 installing modules with PPM, 307 libwin32 modules, 304 log levels, 291 naming conventions, 288

use of .pm extension, 315 online documentation, 290 package hierarchies, 288 package relationship, 288 reasons for using, 287 standard modules, 295

flexible use of command line arguments, 298

network bundle, 312 remote web sites, 311 remote web sites bundle, 311 sound subsystem, 304 storing information in Registry, 305 testing and timing code, 302 traversing directory trees, 297 using long flags, 300 visual representation of data structures,

295 writing portable programs, 301

standard modules list Benchmark module, 302 Data::Dumper module, 295

File::Find module, 297 File::Spec module, 301 Getopt::Long module, 300 Getopt::Std module, 298 list of modules in Perl distribution,

295 Win32::Sound module, 304 Wm32::TieRegistry module, 305

modulo/modulus (%) operator assignment (%=) operators, 39 operator precedence, 24, 36

multiplication (*) operator, 22 assignment(*=) operators, 39 operator precedence, 36

mvcommand renaming files, 220

my() function $ARGV special variable, 188 @ARGV special array, 186 address book example, trees, 248 chess CGI program, 339 declaring arrays, 88 declaring hashes, 114 executing SQL query with DBI, 371 filehandles, 178 lexical scope, 140 lexical variables, 41 use strict statement, 43

MySQL commands CREATE DATABASE, 353 CREATE TABLE, 353 DELETE,382 DESCRIBE, 354 GRANT,354 INSERT,355 REPlACE, 383 SELECT,358 UPDATE,382 USE,353

MySQL database connecting to, 366 executing SQL query with DBI,

367 extracting data, 358

selecting all fields, 358 selecting some fields, 358 selecting some rows, 359

inserting new rows, 355 logging in/ out, 355 non-root user, creating, 354 ordering selected rows, 361

reversing the order, 362 preparing to use, 353 showing all fields, 354 table joins, selecting using, 364 table, creating, 353

419

Page 36: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

420 EX

MySQL server case sensitivity, 352 choosing SQL server, 350 command line interface (CU), 352 creating a database, 352, 353 installation, 350

testing, 351 root user, protecting, 351

mysqlshow command, 351

N \n (newline character), 4, 8

predefined character classes, 159 named parameters, 145

CGI.pm module methods, 329 naming conventions

$ prefix, 111 %prefix, 111 @ prefix, 111 arrays, 87, 111 class names, 256 hashes, 111 modules, 288 packages, 140 programming, 140 scalars, 111 subroutines, 128 variables, 6, 44 variables in packages, 138

nedit web reference for, 3

negated regex match (!-) operator, 35 operator precedence, 36 patterns not matching, 151

negating (A) character class[], 158 negative numbers

unary minus operator, 24 Net::FfP module

transferring files to/from server, 258 new() method

class constructors, 259 object constructors, 257

newline character (\n), 4, 8 predefined character classes, 159

next statement loop labels, 7 4 looping constructs, 72

non-digit (\D) predefined character, 159 non-whitespace (\S) predefined character, 159 non-word(\ W) predefined character, 159 normalization

relational databases, 350 NOT (-) bitwise operator, 26

operator precedence, 36 not (!) Boolean operator, 30

operator precedence, 36

not equal to(!=) comparison operator, 28 not equal to (ne) string operator, 34 NotePad text editor, 3 numbers, 14

binary, 15 conversion into strings, 20 converting strings into numbers, 33 floating point, 15 hexadecimal, 15 integers, 14 numeric comparison operators, 54 octal, 15 predefined character classes, 159 string comparison operators, 34

numeric operators, 22 comparing strings, 34

0 -o file test, 199 object destruction

destroy() method, 281 object -oriented programming, 253

creating a non-00 module, 290 value in Perl, 283

objects accessormethods,271 classes, 255 described, 253

car analogy, 256 object constructors, 257 object destructors, 258

explicit destruction, 281 implicit destruction, 281

perlobj, quote from, 260 what programmers need to know, 256

oct() function conversion to strings, 21

octal numbers, 15 conversion to strings, 20 errors using, 16

octal system, 9 one-to-one correspondences

see hashes online documentation

perldoc program, 290 open() function

append mode(»), 181 arguments, 177 filehandles, writing to files, 191 modes (read/write/append), default, 180 opening files, 177 pipes, 194 piping out to a process, 198 read mode(<), 180 return value, 204 write mode(>), 180

Page 37: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

opendir() directory function, 218 operands, 21 operator precedence, 23, 36

assignment (=, +=, ... ) operators, 38, 39 modulo operator, 24 negative numbers, 24 unary minus operator, 24 using parentheses, 23

operators, 21 addition ( +) operator, 22 AND(&) bitwise operator, 25 and (&&) Boolean operator, 29 arguments, 21 arithmetic operators, 22 arrow notation(->) operator, 35 assignment(=,+=, ... ) operators, 37,39 autodecrement ( --) operator, 39 autoincrement ( ++) operator, 39 bitwise operators, 24 Boolean operators, 29 comma operator (arguments), 35 comparison operators, 27 concatenation(.) operator, 31 conditional operators, 35 described, 13 division (/) operator, 22 exponentiation (**) operator, 23 file test operators, 199 left shift(«) operator, 35 logical operators, 58 modulo(%) operator, 24 multiplication (*) operator, 22 negated regex match (!-) operator, 35 NOT (-) bitwise operator, 26 not (!) Boolean operator, 30 numeric comparison operators, 54 numeric operators, 22 operands, 21 operator precedence, 23, 36 OR Cl) bitwise operator, 26 or Cil) Boolean operator, 30 qw/1 operator, 80 range operators, 35 reference of(\) operator, 36, 231 regexmatch (=-)operator, 35 remainder, 24 repetition (string) operator, 31 right shift (») operator, 35 string comparison operators, 56 string operators, 31 subtraction (-) operator, 22 XOR (")bitwise operator, 26 xor (exclusive or) Boolean operator,

30 OR Cl) bitwise operator, 26

operator precedence, 36

or Cil) Boolean operator, 30 operator precedence, 36 subroutine return values, 145

ord() function finding character's ASCII value, 34

ORDER BY clause SELECT command, MySQL, 361

out of scope variables, 42 output, displaying, 4 ownership

character indicating, 218 file tests, 199 · testing if file is owned, 217

p p() method

CGI.pm module, 327 <p> tags

CGI.pm module generating, 327 package variables

see global variables packages

see also modules creating classes, 264 described, 138 detecting package dependencies,

311 fully qualified variable names, 139 module relationship, 288 naming conventions, 140 package hierarchies, 288 package operator, 139 use strict statement, 140 variables, 138

param() method CGI scripts processing form data,

332 dynamic CGI program, 333

parameters see arguments

parentheses () escaping metacharacters, 155 function arguments, 7 grouping Regex, 161 lists, 78 operator precedence, 36 subroutines, 128, 130

passwords chomp() function, 57 standard input <STDIN>, 57

PATH environment variable whereis command, 214

path() function File::Spec module, 301

paths @INC array, 262

421

Page 38: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

422 INDEX

patterns, 150 see also Regular expressions !- (negated regex match) operator,

151 /regular expression/, 151 =- (regexmatch) operator, 151 anchors, 156 at beginning of string (A), 156

example finding character, 157 at end of string($), 156

example finding string, 157 case sensitivity, 153

i for insensitive, 153 character classes[], 158

negating character class [], 158 predefined character classes, 159 sequences of characters, 159

end of pattern (\E) metacharacter, 156 grouping Regex with parentheses, 161 metacharacters, 155

escaping metacharacters, 155 table summarizing, 164

phrases, string containing, 152 spaces inside the pattern, 152

punctuation, 160 repetition with quantifiers, 162

indefinite repetition, 162 matching one or more times, 163 matching zero or more times, 163 well defined repetition, 164

user/runtime specified patterns, 154 word boundaries, 160 words, not matching, 151 words, string containing, 150

period (.) character escaping metacharacters, 155 pattern matching at end of string, 156

Perl4 declaring subroutines, 133

Perl Package Manager (PPM) installing modules with, 307

perldoc program online documentation, 290 perldoc perlfunc

file tests, 199 perldoc perlmodlib

standard modules listing, 295 perldoc perlvar

special variables, 178 perlmonks website

troubleshooting CGI scripts, 318 perlobj documentation, 260 permissions

file tests, 200 troubleshooting CGI scripts, 318 writing CGI scripts, 317

persistence 00 value in Perl, 284 relational databases, 34 7

Person class completed class, 281 creating classes, 264

phrases pattern matching, 152

pipes I character, 194 described, 194 filehandle reading from, 194, 195 open() function, 194 opening, 194-199 piping in and out of a process, 198 piping in from a process, 194, 195 piping out to a process, 196 reading output of program, 194

placeholders DBI module using joins, 37 4 executing SQL query with DBI, 372

Play() function Win32::Sound module, 304

plurals making words plural, 198

pointers references, 229

polymorphism, 256 pop() array function, 105

modifying referenced array, 237 portability, DBI module, 347 post-increment

autoincrement ( ++) operator, 40 pre-decrement

autodecrement ( --) operator, 40 precedence

see operator precedence predeclaring subroutines, 132 prepare() method, DBI module

executing SQL query with DBI, 368, 370, 371

using placeholders, 373 print() function, 4

arranging in columns, 217 arrays,89 CGI scripts, 322 CGI.pm module, 328

generating HTML without, 324 filehandles, writing to files, 190 list context, 116

arguments in list context, 90 lists, 78

accessing list values, 84 summary, 204 using parentheses, 23

printenv command, 213

Page 39: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

printletter() method Person class, 283 utility methods, 280

private methods, 277 init() method, 279 Person class, 282

procedural programming, 253 processing speed

00 value in Perl, 284 program termination

die() function, 49 exit() function, 48

programming defensive programming, 199 description of programming, 1 documenting, 6 escape sequences, 8 executing a program, 2 file tests, 199 flow chart, 51 indentation, 7 keywords,6 naming conventions, 140 object-oriented programming, 253 packages, 138 procedural programming, 253 source code, 2 statement blocks, 6, 7 subroutines

declaring after invoking, 130 when to use, 127

testing and timing code, 302 using modules, 306 writing portable programs, 301

push() array function, 105 @ARGV special array, 188 modifying referenced array, 237

put() FTP method, 260 pwd() FTP method, 260

Q \Q (special meanings off)

escaping metacharacters, 156 q/ I

single-quoted strings, 19 qq/1

double-quoted strings, 19 quantifiers, 162 question mark (?) character

escaping metacharacters, 155 repetition with quantifiers, 162

quotation marks quotes inside quotes, 18 text inside quotes, 4

quote-like operators (q/ I and qq/ /), 19

qw/ I (quote words) operator creating lists with, 80

R

modifying referenced array, 238 opening and closing delimiters, 80

/regular expression/ patterns, 151

\r (return character), 8 predefined character classes, 159

-r file test, 199 range operators, 35

operator precedence, 36 ranges

lists, 81 RE

see Regular expressions read mode(<), open() function, 180

reading file in list context, 188 reading file in scalar context, 181

readdir() directory function, 218 reading data, 13 reading files

character indicating readable, 218 file tests ( -r), 199 testing if file is readable, 217

readlink() file function, 221 read_in_chessboard() function

chess CGI program, 336, 339 redo statement

looping constructs, 73,74 ref() function, 265 reference of(\) operator

creating reference for existing variable, 231 operator precedence, 36

references, 229-250 ${$ref->} arrow notation, 239 accessing data, 239, 240 anonymous arrays, 232

accessing array, 234 accessing array elements, 236 creating reference to, 234

anonymous data, creating, 230 anonymous hashes, 232 anonymous references, counting, 242 arrays

accessing data in, 239, 240 anonymous arrays, 232, 234, 236 putting references in, 231 storing arrays inside, 231

autovivification, 243 class objects, 267 complex data structures

matrices, 242 trees, 247 using for, 242

423

Page 40: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

424 IN'DEX

counting references to data, 241 creating, 230

automatic creation, 243 example, 241

dereferencing, 233,234 example, 242

destroying, 242 destructors, 276 existing variable, creating for, 230 hashes

accessing data in, 240 anonymous hashes, 232 putting references in, 231 references to, 238

hash keys, reference to, 236 matrices, using for

chessboard example, 244 modifying data referenced, 237 modifying reference, 236 passing arguments by reference, 141 pointers, 229 reference count, 241 references inside references

accessing data in, 239 hashes, 240

referring to same data, 235 scope, 242 using,233 using-> (arrow notation) shorthand,

239 zero reference count, 241

Reg exes see Regular expressions

regex match (=-) operator, 35 counting character occurrences, 210 finding patterns, 151 operator precedence, 36 translating a string, 210

registry storing information in, 305 Wm32::TieRegistry module, 305

regular expression engine, 166 Regular expressions, 149-175

see also patterns !-(negated regexmatch) operator, 151 =- (regexmatch) operator, 151 anchors, 156

common errors writing Regexes, 174 arrays, common errors, 174 backreferences, 165, 174 character classes[], 158 common errors writing, 17 4 data patterns, 149 delimiters

working with Regexes, 170 either-or operator, 161

escaping special characters, 155 common errors writing Regexes,

174 grouping, 161

common errors writing Regexes, 174

join() function, 173 memory, 165 metacharacters, 155 modifiers

i for insensitive, 154 working with Regexes, 171

regular expression engine, 166 split() function, 172 substitution, 168 understanding Regexes, tip on, 156 user/runtime specified patterns, 154

relational databases concurrent access, 347 description, 347 fields, 348 keys, 348 normalization, 350 persistence, 34 7 rows,348 table relationships, 349 tables, 348

remainder see modulo/modulus(%) operator

ren command (Wmdows), 220 rename() FfP method, 260 rename() file function, 220

file tests, 203 repetition (string) operator, 31 REPLACEcommand,383 replication (x) operator

operator precedence, 36 require statement, 262

@INC array, using, 263 do statement compared, 262 translating :: into directory separators,

288 use statement compared, 263

return character (\r), 8 predefined character classes, 159

return values, subroutines, 134 logical OR Cll> operator, 145 returning values explicitly, 136

reverse() function arrayfunctions, 104 hash functions, 122 lists and ranges, 81,82

right shift(») operator, 35 operator precedence, 36

rindex() string function, 208 rm command, 220

Page 41: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

rmdirO directory function, 222 root user, MySQL

creating a non-root user, 354 protecting, 351

rows

s

inserting rows, 355 inserting multiple rows, 357

relational databases, 348

Is modifier, Regexes, 171 \S (non-whitespace character)

predefined character classes, 159 \s (space character)

predefined character classes, 159 -s file test, 199 sill (substitution operator)

working with Regexes, 168 changing delimiters, 170

Sarathy, Gurusamy, 310 scalar context, 90

capturing output using backquotes, 225

hashes, 116 reading file in, 181 reading from file glob, 215

scalars described, 13 naming conventions, 111 scalar variables, 37

scope, 137-141 global variables, 137 lexical variables, 137, 140

example, 275 references, 242 subroutines, 137

scopingvariables, 41 lexical variables, 41 my function, 41 out of scope variables, 42 use strict statement, 42, 43

security, MySQL creating a non-root user, 354

SELECT command, MySQL, 358 ordering selected rows, 361

reversing the order, 362 selecting all fields, 358 selecting some fields, 358 selecting some rows, 359 selecting without joins, 363 use of* (asterisk), 358

sendmail, 196 sessions

00 value in Perl, 284 set command (Windows), 213 set methods, 254

shebang,3 location of interpreter, 4

shell effect of changing directory, 219 system() function, 224

shift() array function, 107 @ARGV special array, 143, 187 accessormethods,272 filehandles, writing to files, 191 modifying referenced array, 237 stopping modification of arguments, 143 without arguments, 269

short circuiting, 145 evaluating statements, 63

significance of bits bitwise operators, 25

single-quoted strings, 17 lists, 80 q/1, 19 quotes inside quotes, 18 variable processing, 17

sleep() function, 94 solutions to exercises

chapter 1, 385 chapter2,385-387 chapter 3, 387-388 chapter 4, 388-388 chapter5,389-390 chapter 6, 390-391 chapter7,392-393 chapter8,393-394 chapter 9, 395-396 chapter 10,396 chapter11,397-400 chapter 12, 401 chapter14,402-403 chapter 15,404

sort command no command line arguments, 183 reading with diamond(<>), 183

sort() array function, 108 filehandles, writing to files, 191, 193

sorting file piping out to a process, 198

sound subsystem module accessing, 304

source code, 2 spaceship comparison operator(<=>), 29 special characters

see metacharacters special variables, 44

$!, 178, 179 $_, 44,217 $1,193 $ARGV, 188 perldoc perlvar, 178

Page 42: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

426 INDEX

split() function chess CGI program, 339 working with Regexes, 172

splitdir() function File::Spec module, 301

splitpath() function File::Spec module, 301

SQL (Structured Query Language) database dialects of, 365 pronunciation, 347

SQLquery executing with DBI, 367

SQLserver choosing MySQL, 350

square brackets [) escaping metacharacters, 155 patterns, 158 references to anonymous arrays,

232 modifying referenced array, 238

stacks pop() and push() functions, 105

standard input, 13 standard input <STDIN>, 46

chomp() function, 47 chop() function, 48 currency conversion program, 47 passwords, 57

standard modules, 295 start_form() method

dynamic CGI program, 335 start_html() function

CGI.pm method, 329 developing CGI scripts, 379

stat of the file, 217 state, CGI script, 335 state handler

executing SQL query with DBI, 368 statements, 6

blocks, 7 ending, 6

static data/methods classes, 255

STDERR standard error, 177 STDIN standard input, 46

currency conversion program, 4 7 described, 177 diamond(<>) reading from, 184 filehandles, 177 while loop, 65

STDOUT standard output, 177 capturing output using backquotes,

225 Stein, Lincoln, 322 strict

see use strict statement

string functions, 206 index() function, 206 length() function, 206 rindex() function, 208 substr() function, 208

string operators, 31 comparing numbers, 34 comparing strings, 56 concatenation operator, 31 equal to (eq) operator, 34 greater than (gt) operator, 34 less than (lt) operator, 34 not equal to (ne) operator, 34 repetition operator, 31 three-way-comparison (cmp) operator,

34 stringifying variables, 90 strings, 17

choosing your own delimiters, 19 converting into numbers, 20, 32

rules, 33 counting character occurrences, 210 data structures, visual representation of,

295 determining length, 206 double-quoted strings, 17 escape sequences, 17 false, definitions of, 27 functions, 206 here-documents, 20 indexing into, 205 long strings, handling, 79 numeric comparison operators, 34 processing strings, 205-211 quote-like operators, 19 removing spaces in, 210 single-quoted strings, 17 substituting individual characters, 210 substrings, extracting, 208 substrings, locating, 206 transliteration operator (tr/ I 1), 210

sub keyword, 128 subclass, 257 subroutines, 128-146

see also functions @ARGV, 136 @_array, 133 arguments, 129

default values, 145, 146 named parameters, 145, 146 passing arrays as, 144 passing into subroutines, 133 passing by reference, 141 passing lists as, 143 stopping modification of, 142

body, 130

Page 43: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

curly brackets {}, 128 declaring, 128

invalid declaration, 131 invoking after, 130 Perl4, 133 predeclaring, 132

described, 127 functions compared, 128 global variables, 137 invoking, 129

declaring after, 130 lexical variables, 137 methods, 255 narningconventions,128 00 value in Perl, 283 parentheses(), 128

declaring after invoking, 130 predeclaring, 132 return values, 134

returning list of values, 135 returning values explicitly, 136 returning values implicitly, 134

scope, 137 scopingvariables, 41 sub keyword, 128 when used, 127

subscripts array index, 93

substitution (sf I!) operator working with Regexes, 168

changing delimiters, 170 substr() string function, 208

left side of assignment, 209 prompting user for arguments,

209 using with Regex, 209

subtraction (-) operator, 22 assignment(-=) operator, 39 operator precedence, 36

superclass, 257 switches

reporting warnings (-w), 4 symlink() file function, 220 syntax errors, 16

troubleshooting CGI scripts, 318 sysread() function, 226 system administration

perldoc perlfunc, 226 system() function, 223

using unlink() function instead, 224

syswrite() function, 226

T \t (tab character), 8, 17 predefined character classes, 159

tab character {\t), 8 escape sequences, 17 predefined character classes, 159

table joins see joins

tables inserting new rows, 355 relational databases, 348

tags CGI.pm module generating, 326 defining tags, 290

templating chess CGI program, 345

terminating program die() function, 49 exit() function, 48

testing MySQL installation, 351 testing and timing code, 302

text text inside quotes, 4 text processing, 205

text editor, choosing, 2 textfield() method

dynamic CGI program, 335 the start_html() method

CGI.pm module, 326 three-way-comparison (cmp) string

operator, 34 timethese() method, Benchmark module, 302 timethis() method, Benchmark module, 302 tmpdir() function, File::Spec module, 301 TMTOWTDI acronym expanded, 302 transliteration operator (tr/ I!), 210-211 traversing

tree structure, 249 trees

address book example, 247 adding another level, 249 deleting data, 249 extracting data, 249 making new entries, 248 printing out data, 248

traversing tree structure, 249 using references for complex data

structures, 24 7 true/truth, 27

testing for truth, 53 type() FTP method, 260 types, field

creating database table, 353

u uc() function, 198 unary minus operator

negative numbers, 24

Page 44: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

428

undef command see also dereferencing chessboard example, matrix, 24 7 removing references, 242

undefined definitions of false, 27

underscore U character default filehandle for file tests, 217 large numbers, handling, 14

Unicode character (\x) , 8 Unix

changing directory, 3 making directories, 3 making files executable, 4 running a Perl file, 3

Perl invocation, 4 Unix commands

chmod command, 4 mkdir command, 3

unless statement, 61 expression modifiers, 62 patterns not matching, 151

unlink() file function, 220, 224 unshiftO array function, 107

modifying referenced array, 237 until loop, 67

expression modifiers, 71 UPDATE command, 382 uppercase

uc() function, 198 USE command, 353 use statement, 263

require statement compared, 263 translating colons into directory

separators, 288 use strict statement

@ARGV special array, 186 address book example, trees, 248 arrays, 88 hashes, 114 my function, 43 packages, 140 Person class, 281 scoping variables, 42, 43

use warnings directive, 5 user/runtime specified patterns, 154 users, MySQL

non-root user, creating, 354 root user, 351

utility methods, 279 fullname() method, 280 Person class, 282 printletter() method, 280

v values() hash function, 118 variables, 37

defined() function, 57 described, 13 global variables, 41, 137 lexical variables, 41, 137 my function, 41 naming conventions, 44

avoiding keywords, 6 fully qualified names, 139 naming meaningfully, 6 packages, 138

processing in quotes, 17 readable variables, 121 scalar variables, 37 scoping,41 special variables, 44 strings, turning into, 90 values

assigning, 37 interpolating, for variable name, 44 modifying,37 no value assigned, 4

vectors, 13 vi, 3 Volume() function

Wm32::Sound module, 304

w -w file test, 199 -woption

converting strings into numbers, 33 -wswitch

reporting warnings, 4 use warnings directive, 5

\w(word) predefined character classes, 159

\W (non-word) predefined character classes, 159

Wall, Larry, 53 wanted() subroutine

File::Find module, 297 warnings

bareword warning, 16 converting strings into numbers, 33 reporting, 4 use warnings directive, 5

web page design chess CGI program, 344

webservers accessing, 316 chess CGI program, 344

Page 45: Exercise Solutions978-1-4302-0665... · 2017. 8. 29. · APPENDIX Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solu tion

choosing Apache, 316 comparison of web servers, 316 localhost, 316 running external programs, 315

web sites templating, 345

WHERE clause AND keyword, 361 SELECT command, 359

using table joins, 364 whereis command, 214 while loop, 63

arrays, looping through, 95 expression modifiers, 70 <STDIN> standard input, 65

whitespace, 4, 8 converting strings into numbers, 33 non-whitespace character, 159 predefined character classes, 159 whitespace characters, 159

widgets form data, 330

Wm32::Sound module, 304 Wm32::TieRegistry module, 305 word boundaries

pattern matching, 160 word processors

using a text editor, 3 WordPad text editor, 3

words pattern matching, 150

word boundaries, 160 predefined word character, 159

non-word character, 159 write mode (>)

open() function, 180 write_out_chessboard() function

chess CGI program, 336 writing to files

X

character indicating can write, 218 file tests, 199 filehandles, 190 testing if can write, 217

-xfiletest, 199 /x (allow whitespace) modifier, Regexes,

171 \x (Unicode character), 8 XOR (")bitwise operator, 26

operator precedence, 36 xor (exclusive OR) Boolean operator, 30

operator precedence, 36

z -z file test, 199 zero

definitions of false, 27

429