First, arrays cannot be undefined. You are checking if the array is empty. To understand why it's being emptied, you need to understand -n
. -n
surrounds your code with
LINE: while (<>) {
...
}
which is short for
LINE: while (defined($_ = <ARGV>)) {
...
}
ARGV
is a magical handle that reads through the files listed in @ARGV
, shifting out the file names as it opens them.
$ echo foo1 > foo
$ echo foo2 >>foo
$ echo bar1 > bar
$ echo bar2 >>bar
$ echo baz1 > baz
$ echo baz2 >>baz
$ perl -nlE'
BEGIN { say "Files to read: @ARGV" }
say "Read $_ from $ARGV. Files left to read: @ARGV";
' foo bar baz
Files to read: foo bar baz
Read foo1 from foo. Files left to read: bar baz
Read foo2 from foo. Files left to read: bar baz
Read bar1 from bar. Files left to read: baz
Read bar2 from bar. Files left to read: baz
Read baz1 from baz. Files left to read:
Read baz2 from baz. Files left to read:
Keep in mind that BEGIN
blocks are executed as soon as they are compiled, so the <ARGV>
hasn't yet been executed when the BEGIN
block is being executed (even though it appears earlier in the program), so @ARGV
hasn't been modified yet.
-n
is documented in perlrun. ARGV
, @ARGV
and $ARGV
are documented in perlvar.