Perl Programming/Filehandles

From Wikibooks, open books for an open world
< Perl Programming
Jump to: navigation, search

← Flow control | Modifiers →


Read files[edit]

Procedural Interface[edit]

By slurping file[edit]

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;

By line processing[edit]

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 input stream 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;
 
}

Object Oriented Interface[edit]

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 @lines;
Previous: Flow control Index Next: Modifiers