Databases Reference
In-Depth Information
while(<INPUTFILE>)
{
# Remove the newline at the end of the line
chomp;
# Split the line by commas
my @AnimalsData=split(",", $_);
# Assign the text before the first comma to the name
my $AnimalName=@AnimalsData[0];
# Assign the text between the first comma and the second comma
# (if any) to the count
my $AnimalCount=@AnimalsData[1];
# Add an entry to the Animals hash for this animal name and
# count pair:
$Animals{$AnimalName}=$AnimalCount;
}
close(INPUTFILE);
# Process the data to calculate the total, then write to the output file
my $Total=0;
print OUTPUTFILE "Pet roll call:\n".
"===========\n";
while ((my $Animal, my $Count) = each(%Animals))
{
print OUTPUTFILE "$Animal:\t$Count\n";
$Total+=$Count;
}
print OUTPUTFILE "===========\n".
"Total:\t$Total\n";
We're providing the name of the output file as the second command-line argument
(
ARGV[1]
). The interesting part of this program starts from the second
open( )
statement;
since we want to write to the file, we add a greater-than (
>
) symbol before the name of
the output file. We also specify the output file handle
OUTPUTFILE
immediately after the
print
command.
If we don't specify an output file handle, program output is sent to the system standard
output, known as
STDOUT
. This is almost always the display screen. As with
STDIN
, we
can use
STDOUT
without needing to explicitly open and close it. We can also print to
standard output by putting
STDOUT
as the file handle in the
print
statement:
print STDOUT "$Animal:\t$Count\n";
Since the program output is sent to standard output by default anyway,
STDOUT
is as-
sumed when no other file handle is specified, and we can safely omit it (as we have in
all our previous scripts):
print "$Animal:\t$Count\n";