Perl Programming/Filehandles

Previous: Advanced output Index Next: Modifiers

Reading 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 that 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 that 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: Advanced output Index Next: Modifiers