develooper Front page | perl.beginners | Postings from February 2002

Re: reading a file line by line

Thread Previous
From:
Brett W. McCoy
Date:
February 27, 2002 12:06
Subject:
Re: reading a file line by line
Message ID:
Pine.LNX.4.43.0202271507440.22349-100000@chapelperilous.net
On Wed, 27 Feb 2002, Jon Serra wrote:

> Greetings,  I am trying to read a text file into a scalar variable line by line
> until EOF or a search test if fullfilled.  I have been reading files in like
> this:
>
> chomp (@line = `cat filename`);
>
> I do not want to do this beacuse my file is quite large, and there is no reason
> to hog the memory for the little bit I actually want, and second, I do not want
> to make a system call to the unix cat command.  TIA Jon

The canonical way to read data from a file in Perl is:

open FHANDLE, "<$filename" or die "Can't open $filename: $!\n";

while(<FHANDLE>) {
	chomp;
	#do stuff with $_
}

close FHANDLE;

See the perldoc on the open function.

-- Brett
                                          http://www.chapelperilous.net/
------------------------------------------------------------------------
"An entire fraternity of strapping Wall-Street-bound youth.  Hell - this
is going to be a blood bath!"
-- Post Bros. Comics


Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About