File Handling
Real Perl scripts open files with open(my $fh, '<', $path) and then read from $fh the same way shown below — but this site's sandboxed execution environment doesn't persist an actual filesystem between runs, so there's no real file to open here. What is practical to demonstrate for real is standard input, which uses exactly the same reading syntax as a file handle, and which this site's own compiler genuinely supports through a separate stdin field you can fill in before running any program.
<STDIN> reads one line at a time from standard input (or returns undef once input is exhausted — which is also how it reads from any file handle, including a real open()'d one). while (my $line = <STDIN>) is the idiomatic way to process input line by line until it runs out:
use strict;
use warnings;
while (my $line = <STDIN>) {
chomp $line;
print "You said: $line\n";
}
You said: hello You said: world
That output is real — this program was actually run with "hello\nworld\n" supplied as stdin. chomp strips the trailing newline that <STDIN> leaves on each line (the newline is part of the line as read; <STDIN> doesn't strip it for you). In list context, the same <STDIN> operator slurps every remaining line at once into a list:
use strict;
use warnings;
my @lines = <STDIN>;
print "Line count: ", scalar(@lines), "\n";
for my $line (@lines) {
chomp $line;
print "- $line\n";
}
Line count: 3 - one - two - three
my @lines = <STDIN>; assigns to an array, so (exactly as the context lesson described) Perl evaluates <STDIN> in list context and it returns every remaining line as a list, rather than just the next one. Next: error handling — die, eval, and $@.
Practice exercise
Read a line from STDIN into my $name, chomp off the trailing newline, then print "Hello, " followed by $name and "!".