← Back to Perl Course | Chapter 5: File I/O | Lesson 7 of 7

Standard streams and in-memory files

STDIN, STDOUT and STDERR are always open, and you can even open a string as if it were a file.

Standard streams and in-memory files

Perl opens STDIN for input, STDOUT for normal output and STDERR for errors and warnings before your program starts. print writes to STDOUT by default, and you can direct output elsewhere by naming a handle. Opening a reference to a scalar variable as a file lets you read or write a string with the same file functions, which is very handy for testing.

Note: STDERR is not buffered the same way as STDOUT, so error messages may appear out of order with normal output.

Example: Standard streams and in-memory files

perl
use strict;
use warnings;

print STDOUT "normal output\n";
print STDERR "an error message\n";

my $buffer = '';
open(my $mem, '>', \$buffer) or die "Cannot open in-memory file: $!";
print $mem "line one\n";
print $mem "line two\n";
close $mem;
print "buffer holds ", length($buffer), " characters\n";

open(my $read, '<', \$buffer) or die "Cannot read in-memory file: $!";
while (my $line = <$read>) {
    chomp $line;
    print "got: $line\n";
}
close $read;

# Output:
# normal output
# buffer holds 18 characters
# got: line one
# got: line two
Common Mistakes
  1. Printing errors to STDOUT instead of STDERR
  2. Forgetting that STDIN reads a line including its newline
  3. Forgetting to close an in-memory write handle before reading the string
Chapter Summary
  • STDIN, STDOUT and STDERR are always available
  • print goes to STDOUT by default
  • Warnings and die messages go to STDERR
  • open a scalar reference to use a string as a file
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.