Any time we call the diamond operator, we read a line from the associated file (assumed as a text file). If we are at its end, an undef value is returned. If we are working with a "real" file, a bunch of data stored in the file system, it is quite clear what this means. A bit fuzzier is in case of a stream, like what happens when we use standard input.
To signal that we consider close our stream from standard input to our perl application we use a ctrl-Z (Windows) or ctrl-D (UNIX).
Here is a while loop that run on the standard input till we signal we have got enough of it, and echo the line we entered:
while(defined($_ = <STDIN>)) {
print "---> $_";
}
print "Done\n";
We can rewrite this loop in this way:
while(<>) {
print "---> $_";
}
The latter is more flexible, since it normally works on STDIN, but we can use another file simply passing it as argument to the perl script on the command line.
Chapter 4 of Beginning Perl by Simon Cozens is about loops and decisions.
No comments:
Post a Comment