Databases Reference
In-Depth Information
while ((my $Animal, my $Count) = each(%Animals))
{
print "$Animal:\t$Count\n";
$Total+=$Count;
}
print "===========\n".
"Total:\t$Total\n";
We can then run this as:
$ ./Animals.command_line.tofile.pl < animals.csv
or as:
$ cat animals.csv | Animals.command_line.tofile.pl
on a Linux or Mac OS X system, or as:
$ type animals.csv | Animals.command_line.tofile.pl
on a system running Windows.
Writing values to a file or standard output
You'll often want to permanently store the output of your program in a file. Exam-
ple 16-9 modifies the program to take a second command-line argument to specify the
name of the output file.
Example 16-9. Perl script to read in data from a CSV file and save results to an output file
#!/usr/bin/perl
use strict;
my %Animals;
# If the user hasn't provided any command-line arguments, provide a
# helpful error message.
if(@ARGV!=2)
{
die("Syntax: $0 [Input file] [Output file]\n");
}
# Open the file specified on the command line; if we can't open it,
# print an error message and stop.
if(!open(INPUTFILE, $ARGV[0]))
{
die("Failed opening $ARGV[0]\n");
}
# Open the output file specified on the command line; if we can't open it,
# print an error message and stop.
if(!open(OUTPUTFILE, ">$ARGV[1]"))
{
die("Failed opening $ARGV[1]\n");
}
# Read in from input file line by line; each line is
# automatically placed in $_
 
Search WWH ::




Custom Search