10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

APPENDIX ■ PERL BASICS 327Counting down: 2Counting down: 1$Let’s see a flow chart for this program. While there’s still a value greater than 0 in the$counter variable, we do these two statements:print "Counting down: $countdown\ n";$countdown--;<strong>Perl</strong> goes through the loop a first time when $countdown is 5—the condition is met, soa message gets printed, and $countdown gets decreased <strong>to</strong> 4. Then, as the flowchart implies,back we go <strong>to</strong> the <strong>to</strong>p of the loop. We test again: $countdown is still more than 0, so off we goagain. Eventually, $countdown is 1, we print our message, $countdown is decreased, and it’s now0. This time around, the test fails, and we exit the loop.while ()Recall that we talked about using <strong>to</strong> read from standard input (normally the keyboard).This statement reads the next line of standard input, up <strong>to</strong> and including the newline character:$line_in = ;We can put this assignment within a while loop that will read from standard input untilend of file (in Unix a ^D or Ctrl+D; in Windows a ^Z). This loop reads a line at a timein<strong>to</strong> $line_in and then prints the line read in:while ($line_in = ) {print $line_in;}This behavior, reading from standard input until end of file, is so common that if is by itself within the while loop parentheses (and only within the while loop parentheses),then the line of standard input is magically assigned <strong>to</strong> the special variable $_. This loop readseach line in<strong>to</strong> $_, and then the line is printed:while () {print $_;}This is so common that print() defaults <strong>to</strong> printing $_:while () {print;}Let’s look at an example of using this magic variable $_. This program will loop throughstandard input one line at a time until end of file, and for each line it will print a message followedby the line entered:#!/usr/bin/perl -w# while2.pl

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!