Databases Reference
In-Depth Information
Every standard Perl function ends by passing back a value to the code that called it. In
fact, many functions do nothing
but
return a value. The
open( )
function returns a
nonzero value to indicate that it succeeded in opening the file, and returns zero if it
failed. Common causes of file-access errors include mistyped filenames and insufficient
privileges to access a particular file or directory. We can use an
if
statement to check
for a zero value; if the file-open operation failed, we can use the
die( )
function to
display an error message and stop the script:
if(!open(INPUTFILE, $ARGV[0]))
{
die("Failed opening $ARGV[0]\n");
}
This combination of an
if
statement and an
open
function is worth noting; we've pre-
viously used
if
on logical tests such as
$Username == "Ali"
, but
if
is flexible enough
to directly test a single value, or the result of a function such as
open
. We can also use
the simpler
or
construct to call the
die( )
function if the
open( )
function fails:
open(INPUTFILE, $ARGV[0])
or
die("Failed opening $ARGV[0]\n");
Save this program as
readfile.pl
, and then get it to read in and display the contents of
the
animals.csv
file:
$
./readfile.pl animals.csv
cats,2
dogs,5
fish,3
emus,4
Instead of simply printing out the file contents, let's load them into our own data
structures and process the data. We have to remove the invisible newline at the end of
each line of the text file using the
chomp( )
function, then load the contents of each line
into array elements by the location of the commas using the
split( )
function. For
convenience, we assign the first value to the scalar variable
$AnimalName
and the second
value to the scalar variable
$AnimalCount
. We then use these to populate the
%Animals
hash.
For example, the line:
cats,2
is split at the comma into the
@AnimalData
array, with:
AnimalsData[0]: cats
AnimalsData[1]: 2
and these values are assigned to the variables:
AnimalName: cats
AnimalCount: 2
The statement: