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.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Printing errors to STDOUT instead of STDERR
- Forgetting that STDIN reads a line including its newline
- 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: