Opening and Closing Files in Perl

   



Reading Files in Perl

Listing C.8 displays the contents of the file somedata.txt that we will use for the purposes of illustrating how to read the contents of a file.

Listing C.8 somedata.txt

start example
# this is a comment line Jones:Tom:1000 Smith:Ann:2000 Smith:Bill:3000
end example

Listing C.9 displays the contents of readFile1.pl, which is a Perl script that reads the contents of the file somedata.txt.

Listing C.9 readFile1.pl

start example
my($count)       = 0; my($currentLine) = ""; my($fileName)    = "somedata.txt"; open(INPUT, "<$fileName") || die "Cannot open $fileName: $!\n"; while($currentLine = <INPUT>) {    $count++; } print "File $fileName contains $count lines\n";
end example

Remarks

You can launch the Perl script readFile1.pl in Listing C.9 from the command line as follows:

perl -w readFile1.pl

If the file was opened successfully, you will see the following output:

File somedata.txt contains 5 lines



   



Fundamentals of SVG Programming. Concepts to Source Code
Fundamentals of SVG Programming: Concepts to Source Code (Graphics Series)
ISBN: 1584502983
EAN: 2147483647
Year: 2003
Pages: 362

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net