In Perl, it’s normally easy enough to get a reference to the commandline arguments. I just use $ARGV[0] for example to get the name of a file that was passed in as the first argument.
When using a Perl one-liner, however, it seems to no longer work. For example, here I want to print the name of the file that I’m iterating through if a certain string is found within it:
perl -ne 'print $ARGV[0] if(/needle/)' haystack.txt
This doesn’t work, because ARGV doesn’t get populated when the -n or -p switch is used. Is there a way around this?
What you are looking for is
$ARGV. Quote from perlvar:So, your one-liner would become:
Though be aware that it will print once for each match. If you want a newline added to the print, you can use the
-loption.If you want it to print only once for each match, you can close the ARGV file handle and make it skip to the next file:
As Peter Mortensen points out,
$ARGVand$ARGV[0]are two different variables.$ARGV[0]refers to the first element of the array@ARGV, whereas$ARGVis a scalar which is a completely different variable.You say that
@ARGVis not populated when using the-por-nswitch, which is not true. The code that runs silently is something like:Which in essence means that using
$ARGV[0]will never show the real file name, because it is removed before it is accessed, and placed in$ARGV.