Perl Programming/Filehandles
From Wikibooks, the open-content textbooks collection
Contents |
[edit] Read files
[edit] Procedural Interface
[edit] By globbing file
This method will read the whole file into an array. It will split on the special variable $/
# Create a read-only file handle for foo.txt open ( my $fh, '<', 'foo.txt' ); # Read the lines into the array @lines my @lines=<$fh>; # Print out the whole array of lines print @lines;
[edit] By line processing
This method will read the file one line at a time. This will keep memory usage down, but the program will have to poll the hard drive on each iteration.
# Create a read-only file handle for foo.txt open ( my $fh, '<', 'foo.txt' ); # Iterate over each line, saving the line to the scalar variable $line while ( my $line = <$fh> ) { # Print out the current line from foo.txt print $line; }
[edit] Object Oriented Interface
Using IO::File you can get a more modern object-oriented interface to a perl file handle.
# Include IO::File which will give you the interface use IO::File; # Create a read-only file handle for foo.txt my $fh = IO::File->new( 'foo.txt', 'r' ); # Iterate over each line, saving the line to the scalar variable $line while ( my $line = $fh->getline ) { # Print out the current line from foo.txt print $line; }
# Include IO::File which will give you the interface use IO::File; # Create a read-only file handle for foo.txt my $fh = IO::File->new( 'foo.txt', 'r' ); my @lines = $fh->getlines; # Print out the current line from foo.txt print $line;

