Databases Reference
In-Depth Information
my $Total=0;
print "Pet roll call:\n".
"===========\n";
while ((my $Animal, my $Count) = each(%Animals))
{
print "$Animal:\t$Count\n";
$Total+=$Count;
}
print "===========\n".
"Total:\t$Total\n";
Reading in values from standard input
The console's standard input is a special file that captures data typed in at the console,
sent to the program using a pipe ( | ), or read from a redirection operator ( < ). Using the
standard input, we can skip the process of opening and closing the file using the file
pointer ( INPUTFILE in our example), and instead use the built-in Perl STDIN file handle,
as shown in Example 16-8.
Example 16-8. Perl script to read in data from a CSV file from standard input
#!/usr/bin/perl
use strict;
my %Animals;
# Read in from standard input line by line; each line is
# automatically placed in $_
while(<STDIN>)
{
# Remove the newline at the end of the line
chomp($_);
# Split the line by commas and load it into the AnimalsData array
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;
}
# Process the data to calculate the total; code beyond this point is
# identical to our previous example and doesn't deal with the
# command-line arguments.
my $Total=0;
print "Pet roll call:\n".
"===========\n";
 
Search WWH ::




Custom Search