Beginning Perl Third Edition PHẦN 10 docx

50 488 0
Beginning Perl Third Edition PHẦN 10 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

CHAPTER 15 ■ PERL AND DBI 384 my($phone); ($phone) = $sth->fetchrow(); # print number and end HTML print "Call $musician at $phone.", end_html; After calling Geddy Lee, our music fan might want to see the instruments Thom Yorke plays, so our curious person goes back to the initial page, select Thom from the drop-down menu, and clicks Show instruments. That produces this page: And here’s the code that builds the page: } elsif (param('Show instruments')) { # the user wants to see the instruments the musician # plays, start the HTML print header(), start_html("Instruments played by $musician"), h1("Instruments played by $musician"), "$musician plays:", '<ul>'; CHAPTER 15 ■ PERL AND DBI 385 We see that the user wants to show the musician’s instruments, so we start the HTML, print some text, and then start an unordered list (a bullet list). Then we go to the code that queries the database: # query the database with a table join and retrieve the # instruments played by musician my $dbh = DBI->connect("DBI:mysql:musicians_db", "musicfan", "CrimsonKing"); my $sth = $dbh->prepare("SELECT instrument FROM instruments JOIN what_they_play ON instruments.inst_id = what_they_play.inst_id JOIN musicians ON what_they_play.player_id = musicians.player_id WHERE musicians.name = ?") or die "prepare failed: " . $dbh->errstr(); $sth->execute($musician) or die "execute failed: " . $sth->errstr(); Using the table join we’ve seen a few times in this chapter, we find all the instruments that the musician plays, bringing us to the code that prints the instruments: my($instrument); # print all the instruments in a bullet list while (($instrument) = $sth->fetchrow()) { print "<li>$instrument</li>"; } Notice that each instrument is printed within an <li> tag, which makes it into a bullet item in the list. Finally we get to the end of the unordered list and the end of the HTML: # finish the HTML print '</ul>', end_html; } That was fun! And using Perl, CGI, and DBI it was easy as well. Such is the power and practicality of Perl revealed. What We Didn’t Talk About This chapter isn’t meant to be an exhaustive discussion of SQL and DBI. There are many topics we didn’t talk about that you should learn if you want to harness the maximum power of SQL. First, there are several essential commands, including the following: • UPDATE: Allows data in a table to be modified. An example might be UPDATE musicians SET phone = "555-9999" WHERE player_id = 3; CHAPTER 15 ■ PERL AND DBI 386 • DELETE: Deletes a row from a table. An example might be DELETE FROM instruments WHERE inst_id = 13; Be careful! If you don’t use the WHERE clause, you’ll delete all rows in the table. • REPLACE: If the key provided does not exist, the data is inserted; otherwise the row with that key is first deleted, then the new row is inserted. An example might be REPLACE INTO musicians (player_id, name, phone) VALUES (1, "Neil Peart", "555-8888"); Just as knowing these SQL commands is important, so is understanding table indexing. Indexing can significantly increase the speed of SELECT statements with large tables. See the docs for more information. Also, be sure to check out Michael Kofler’s excellent book, and remember to look at the online documentation for MySQL at http://dev.mysql.com/doc/refman/5.1/en/. Summary In this chapter we described how to access a database using Perl and the DBI module. We started with a description of a relational database and followed with a brief introduction to SQL. We then installed MySQL, created a database with three tables, and talked about several SQL commands. INSERT and SELECT were the most important ones. We also discussed using table joins as a way to implement the relations in relational databases. After that, we introduced DBI and DBD::mysql and wrote several Perl scripts to access and query the database. We ended with an example that showed how easily you can create dynamic web content by connecting Perl, DBI, and CGI.pm. And in the middle of that discussion, we took time out of our busy day to call one of our favorite musicians. Exercises 1. Write a Perl script that prompts the user for an instrument and then prints all the musicians that play that instrument. 2. Write a CGI program similar to musicians.pl that serves as a web interface to the script you created for exercise 1. A P P E N D I X ■ ■ ■ 387 Exercise Solutions This appendix contains the answers to the chapter exercises. An important note: each solution 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 # chap01ex1.pl use warnings; print "Hi Mom.\nThis is my second program.\n"; Chapter 2 1. #!/usr/bin/perl # chap02ex1.pl use warnings; use strict; print "Currency converter\n\n"; print "Please enter the exchange rate: "; chomp(my $yen = <STDIN>); APPENDIX ■ 388 print "Enter first price to convert: "; chomp(my $price1 = <STDIN>); print "Enter second price to convert: "; chomp(my $price2 = <STDIN>); print "Enter third price to convert: "; chomp(my $price3 = <STDIN>); print "$price1 Yen is ", ($price1/$yen), " dollars\n"; print "$price2 Yen is ", ($price2/$yen), " dollars\n"; print "$price3 Yen is ", ($price3/$yen), " dollars\n"; 2. #!/usr/bin/perl # chap02ex2.pl use warnings; 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. #!/usr/bin/perl # chap02ex3.pl use warnings; use strict; print "enter a value less than 256: "; chomp(my $bin = <STDIN>); print((128 & $bin) / 128); print((64 & $bin) / 64); print((32 & $bin) / 32); print((16 & $bin) / 16); print((8 & $bin) / 8); print((4 & $bin) / 4); print((2 & $bin) / 2); www.wowebook.com APPENDIX ■ 389 print((1 & $bin) / 1); print "\n"; 4. (2 + (6 / 4) - (3 * 5) + 1) = -10.5 (17+((-(3**3))/2)) = 3.5 ((26+3)^(4*2)) = 21 (((4 + 3) >= 7) || (2 & ((4 * 2) < 4))) = 1 Chapter 3 1. #!/usr/bin/perl # chap03ex1.pl use warnings; use strict; my $target = 12; print "Guess my number!\n"; print "Enter your guess: "; my $guess; while ($guess = <STDIN>) { if ($target == $guess) { print "That's it! You guessed correctly!\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: "; } 2. #!/usr/bin/perl # chap03ex2.pl APPENDIX ■ 390 use warnings; use strict; for (my $i = 1; $i <= 10; $i++) { print "$i square is: ", $i*$i, "\n"; } 3. #!/usr/bin/perl # chap03ex3.pl use warnings; use strict; for (my $i = 1; $i <= 50; $i++) { if ($i % 5 == 0) { print "$i is evenly divisible by 5\n"; } } Chapter 4 1. #!/usr/bin/perl # chap04ex1.pl use warnings; use strict; my @a = (2, 4, 6, 8); foreach (@a) { print "$_ ** 2 = ", $_ ** 2, "\n"; } foreach (reverse @a) { print "$_ ** 2 = ", $_ ** 2, "\n"; } APPENDIX ■ 391 3. Here is a program that illustrates the answer to this question. #!/usr/bin/perl # chap04ex3.pl use warnings; use strict; my @a = ('aa' 'bb'); print "first array:\n"; print "@a\n"; @a = ('a0' 'b9'); print " \n"; print "second array:\n"; print "@a\n"; Chapter 5 1. #!/usr/bin/perl # chap05ex1.pl use warnings; use strict; my %hash = ( scalar => 'dollar sign', array => 'at sign', hash => 'percent sign' ); foreach (sort keys %hash) { print "$_: $hash{$_}\n"; } 2. #!/usr/bin/perl # chap05ex2.pl APPENDIX ■ 392 use warnings; 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{$_}) { print "$_ has the phone number: $phonenumbers{$_}\n"; } else { print "$_ is not in the phone book\n"; } print "enter name: "; } 3. #!/usr/bin/perl # chap05ex3.pl use warnings; 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"; } APPENDIX ■ 393 print "enter programming language: "; } Chapter 6 1. #!/usr/bin/perl # chap06ex1.pl use warnings; use strict; print "enter a number: "; chomp(my $input_num = <STDIN>); if ($input_num < 0) { print "please enter a positive number!\n"; } else { my $result = factorial($input_num); print "$input_num! = $result\n"; } sub factorial { my $num = shift; if ($num == 0) { return 1; } else { my $answer = 1; foreach (2 $num) { $answer = $answer * $_; } return $answer; } } 2. #!/usr/bin/perl # chap06ex2.pl use warnings; use strict; print "enter a number: "; [...]... array elements, references and, 238 array indexes (array subscripts), 97 array slices, 101 arrays, 81, 91–114, 231–235 accessing, 95 109 adding elements to, 95, 109 anonymous, 234, 251 attributes and, 298 converting to hashes, 116 exists() function and, 124 for loop and, 100 foreach loop and, 101 , 103 functions for, 109 arrow notation (->), 241 matrices and, 245 methods and, 289 ASCII character set,... command), 364 ■C -c option, for checking Perl syntax, 4 canonpath() function, 273 backwhacking characters, 17–20 carat (^) metacharacter, as anchor, 159, 160, 167 barewords, 16 Carp module, 285 base 10 (decimal system), 10 carp() function, 285 base 16 (hexadecimal system), 10 case sensitivity base 2 (binary system), 10 classes and, 289 base 8 (octal system), 10 lc() function and, 199 BEGIN subroutine,... 72, 2; 75, 5; APPENDIX ■ 2 #!/usr/bin /perl # chap09ex2.pl use warnings; use strict; while () { tr/a-zA-Z/n-za-mN-ZA-M/; print; } Chapter 10 1 #!/usr/bin /perl # chap10ex1.pl use warnings; use strict; my $dir = shift || ''; my $size = shift || ''; die "usage: chap10ex1.pl \n" unless $dir and $size; chdir $dir or die "can't chdir: $!"; # first, a file glob # this gets hidden files too print... filenames, File::Spec and, 273 files, 179–206, 217–225 autoclosing and, 180 ■ INDEX closing, 180 arrays and, 101 , 103 deleting, Hoover program and, 270 breaking out of, 75 do statement and, 260 counting items, hashes and, 128 file gobbing and, 217 expression modifiers and, 108 File::Find and, 270 syntax for, 103 file size and, 219 fork() function, 228 file slurps and, 190, 196, 276 Format() function, 277 File::Spec... 271, 272 flattened lists, 84, 86, 95 floating-point numbers, 14, 15, 21 flock() function, 259 flow charts, 53 flow of execution, of programs, 53 for keyword, 72, 108 for loop, 71 arrays and, 100 breaking out of, 75 foreach keyword, 72, 103 , 108 foreach loop, 71 get() function, 284 get() method, Net::FTP and, 294 Getopt::Long, 271, 272 Getopt::Std, 271 getopts() function, 272 getprint() function, 284... variables, 72, 103 close() function, 180 conversion utility (sample program), 140–142 code for this book, downloading, 12 counting items colon (:), data sources and, 369 via hashes, 126–129, 198 columns, extracting fields from strings and, 210 pitfalls to avoid with, 176 command line interface (CLI), 354 pluralizing items and, 200 command-line arguments @ARGV variable and, 187 CPAN (Comprehensive Perl Archive... of the same character 2 /^\d.*\d$/ /^[\s\w]+$/ /^\S*$/ 3 #!/usr/bin /perl # chap07ex3.pl use warnings; use strict; while () { print if /[aeiouy][aeiouy]/i; } 4 #!/usr/bin /perl # chap07ex4.pl 395 APPENDIX ■ use warnings; use strict; while () { print if /^[^aeiouy]*[aeiouy][^aeiouy]*[aeiouy][^aeiouy]*$/i; } Chapter 8 1 #!/usr/bin /perl # chap08ex1.pl use warnings; use strict; open(INFH, ' . 2. #!/usr/bin /perl # chap09ex2.pl use warnings; use strict; while (<>) { tr/a-zA-Z/n-za-mN-ZA-M/; print; } Chapter 10 1. #!/usr/bin /perl # chap10ex1.pl use warnings;. DBD::mysql and wrote several Perl scripts to access and query the database. We ended with an example that showed how easily you can create dynamic web content by connecting Perl, DBI, and CGI.pm 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 # chap01ex1.pl use warnings;

Ngày đăng: 09/08/2014, 14:21

Mục lục

    What We Didn’t Talk About

Tài liệu cùng người dùng

Tài liệu liên quan