Databases Reference
In-Depth Information
Notice that the counts aren't aligned properly; this is because the longer animal names
(giraffes and elephants) reach the end of the first tab column, and so the \t in the
print statement moves the count into the next tab column.
Reading in values from a file
Instead of typing in the data as command-line arguments, we can ask our program to
read in the data from a file. A popular and simple format for data interchange between
applications is the comma-separated values (CSV) format. This is a plain-text format
with the data separated by commas. Create the following CSV file in a text editor and
save it as animals.csv :
cats,2
dogs,5
fish,3
emus,4
Now, let's write a simple program to read in a specified file and print the contents on
the screen. Example 16-6 uses the open function to open the file and a while loop to
read it in line by line.
Example 16-6. Perl script to read in a text file and display the contents
#!/usr/bin/perl
use strict;
# If the user hasn't provided one command-line argument, provide a
# helpful error message.
if(@ARGV!=1)
{
die("Syntax: $0 [Input file]\n");
}
# Open the file specified on the command line; if we can't open it,
# print an error message and stop.
open(INPUTFILE, $ARGV[0])
or die("Failed opening $ARGV[0]\n");
# Read in the input file line by line
while(my $Line=<INPUTFILE>)
{
print $Line;
}
# Close the input file
close(INPUTFILE);
Here, we've used the open( ) function to open the file with the name specified on the
command line and configure a file handler to access this file; in our example, we've
used INPUTFILE for the file handler. Note that unlike other types of Perl variables, file
handlers don't have a symbol such as the dollar symbol ( $ ) or the at symbol ( @ ) before
them.
 
Search WWH ::




Custom Search