28 Feb
Posted by rdash as Perl tips, Programming
Reading all the lines of a data file is a very basic operation. Perl lets you do this in a number of ways. The method of feeding the data file to the Perl program can either be a redirect from the command line, or through a specified filename:
This tutorial covers the first case. The next tutorial will cover the second case. Here is some sample code. Error-checking is left for later tutorials. This tutorial will be the basis of much of the future file manipulation examples.
#!/usr/bin/perl
######################
#
# FILE: readfile01.pl
#
######################
#
# Read all the lines of an input data file
# and print each line out with a line number.
#
use strict; # Declare strict checking on variable names, etc.
#
# While there are lines to read from standard input, loop
#
my $lnum; # Initialize line counter
while (<STDIN>)
{
# The <STDIN> operator assigns the next line of data
# from standard input to the Perl system variable $_.
# You can also write <> instead of <STDIN>.
#
$lnum++; # Increment the line counter
chomp; # Remove the 'newline' character, '\n', from $_
print "$lnum: $_\n"; # Print the line number and line
}
exit(0); # Exit gracefully
This is #3 in a series of Perl scripts. Please feel free to leave comments if there is something that you would like to see. I cannot guarantee that I’ll be able to answer immediately, but I will answer as soon as I can.
Technorati Tags: webguru, perl-tips, perl scripts, web programming
2 Responses
Randal L. Schwartz
March 3rd, 2006 at 11:46 am
1Instead of $lnum, just use the built-in “$.” variable. Much simpler.
rdash
March 3rd, 2006 at 2:28 pm
2Agreed. Forgot about “$.”; don’t use it much because I usually have to alter the line number in my own coding projects.
RSS feed for comments on this post · TrackBack URI
Leave a reply
Categories
Archives
Links
Meta
Calendar