Input/Output
Beginning |
Previous |
Next
Keyboard and Screen I/O
As mentioned before, you can use the predefined file handles,
STDIN and STDOUT to read from the keyboard
and write to the screen respectively, such as:
my ($in, $half);
print STDOUT "Enter a max value, goober > ";
$in = ;
chomp ($in);
$half = $in / 2.0;
print STDOUT "Half of $in = $half\n";
Note: print() will print to a file handle. If none is
supplied, STDOUT is the default.
Opening Files
The general format for opening a file can be given as:
open (FILEHANDLE, EXPR);
The format I would recommend is:
open (FILEHANDLE, EXPR) or die "Can't open FILENAME: $!\n";
where FILENAME is the file you tried to open in
EXPR. If the filename begins with ">>" ,
the file is opened for appending. (You can put a "+" in
front of the ">" or "<" to indicate that you
want both read and write access to the file.) If the filename begins
with "|", the filename is interpreted as a command to which
output is to be piped, and if the filename ends with a "|",
the filename is interpreted as command which pipes input to us. (You
may not have a command that pipes both in and out.) For example:
# open a file for reading
open (INIT_FILE, '.emacs') or die "Can't open .emacs: $!\n";
# open a file for writing, note double quote for interpolation
open (LOG, ">$log") or die "Can't open $log: $!\n";
my (@contents, $line, $count);
@contents = ; # read in the entire contents of the file
close (INIT_FILE); # done with file, close handle
$count = 1;
foreach $line (@contents)
{
print LOG ("$count: $line"); # print line number w/ line
$count++; # increment line number
}
close (LOG);
Another way of doing this is:
my (@contents, $line, $count);
open (INIT_FILE, '.emacs') or die "Can't open .emacs: $!\n";
open (LOG, ">.emacs.lines") or die "Can't open .emacs.lines: $!\n";
$count = 1;
# read in one line at a time, till we reach EOF
while ($line = )
{
print LOG ("$count: $line"); # print line number w/ line
$count++; # increment line number
}
close (INIT_FILE);
close (LOG);
Reading Directory Contents
Some handy built-in routines exist for reading the contents of a
directory, for example, we can get the contents of the current
directory, minus the "." and ".." files with:
my (@files);
opendir (DIR, '.') or die "Can't open current dir: $!\n";
@files = grep (!/^\.\.?$/, readdir (DIR));
closedir (DIR);
Beginning |
Previous |
Next
Last Modified: $Date: 1997/09/18 08:51:42 $