1.4 Filehandles
Unless you're using artificial intelligence to model a solipsistic philosopher,
your program needs some way to communicate with the outside world. In
lines 3 and 4 of our grade example you'll see the word Filehandles make it easier for you to get input from and send output to many different places. Part of what makes Perl a good glue language is that it can talk to many files and processes at once. Having nice symbolic names for various external objects is just part of being a good glue language.[ 17 ]
You create a filehandle and attach it to a file by using the
open
function.
open
takes two parameters: the filehandle and the filename
you want to associate it with. Perl also gives you some predefined (and
preopened) filehandles.
Since you can use the open function to create filehandles for various purposes (input, output, piping), you need to be able to specify which behavior you want. As you would do on the UNIX command line, you simply add characters to the filename.
open(SESAME, "filename"); # read from existing file open(SESAME, "<filename"); # (same thing, explicitly) open(SESAME, ">filename"); # create file and write to it open(SESAME, ">>filename"); # append to existing file open(SESAME, "| output-pipe-command"); # set up an output filter open(SESAME, "input-pipe-command |"); # set up an input filter
As you can see, the name you pick is arbitrary.
Once opened, the filehandle
Once you've opened a filehandle for input (or if you want to use
print STDOUT "Enter a number: "; # ask for a number $number = <STDIN>; # input the number print STDOUT "The number is $number\n"; # print the number
Did you see what we just slipped by you? What's the
We also did something else to trick you. If you try the above
example, you may notice that you get an extra blank line. This
happens because the read does not automatically remove the newline
from your input line (your input would be, for example,
"
chop($number = <STDIN>); # input number and remove newline which means the same thing as
$number = <STDIN>; # input number chop($number); # remove newline |
|