perldiamond-operatorscalar-context

Perl ARGV value in scalar context


Given the following Perl script:

# USAGE: ./flurp -x -vf file1 file2 file3 file4

# e.
$a = shift;
$b = shift;
$c = shift;
@d = <>;

# ei.  value of $b = -vf
# eii. value of @d = content of file2, file3, file4

print "$b\n";
print "@d\n";
print "$ARGV\n";

This is the output:

-vf
{contents of file2, file3, file4}
file4

I am puzzled by the output of print "$ARGV\n". If I try to do print "$ARGV[-1]\n", an empty line is printed out to STDOUT. If I directly reference $ARG[2], I get an empty line as well.

Why is the script printing file4 when $ARGV is used?

As a counter-example, I tried print "$d\n", expecting to get the last line of file4. Instead of the expected output I got an empty line. How does $ARGV work?


Solution

  • In answer to your specific question: "How does $ARGV work?"

    $ARGV Contains the name of the current file when reading from <> .

    from Variables related to filehandles in the Perl docs.

    Although at the point you print $ARGV you've finished reading from file4, the variable still holds the name of the file.