Skip to content
File I/O
step 1/4

Reading — step 1 of 4

Learn

~1 min readModules and OOP

Perl was born for text processing. File handling is direct.

Reading line-by-line:

open(my $fh, '<', 'data.txt') or die "can't open: $!";
while (my $line = <$fh>) {
    chomp $line;
    process($line);
}
close $fh;

The <$fh> operator reads one line including \n. chomp strips it.

Slurp the whole file:

open(my $fh, '<', 'data.txt') or die $!;
my @lines = <$fh>;            # array context — all lines
my $contents = do { local $/; <$fh> };   # one big string
close $fh;

Writing:

open(my $out, '>', 'output.txt') or die $!;   # truncate + write
open(my $out, '>>', 'output.txt') or die $!;  # append
print $out "hello\n";
close $out;

Modes:

  • < — read
  • > — write (truncate)
  • >> — append
  • +< — read+write
  • |- and -| — pipe to/from a command

Special filehandles:

  • STDIN, STDOUT, STDERR always open
  • <STDIN> reads from stdin (what you've been using)
  • print STDERR "oops\n"; writes to stderr

__DATA__ lets you embed data in the script:

while (my $line = <DATA>) { print $line; }
__DATA__
first line
second line

-e, -f, -d, -r etc. are file tests:

if (-f "/path/to/file") { ... }   # file exists and is regular
if (-d "dir") { ... }              # directory

File::Slurper (CPAN) gives nicer one-liners but isn't core.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…