Search code examples
perl

How can I get the filename when using the <> Perl construct?


Perl offers this very nice feature:

while ( <> )
{
    # Do something
}

...which allows the script to be used as script.pl <filename> as well as cat <filename> | script.pl.

Now, is there a way to determine if the script has been called in the former way, and if yes, what the filename was?


Solution

  • The variable $ARGV holds the current file being processed.

    $ echo hello1 > file1
    $ echo hello2 > file2
    $ echo hello3 > file3
    $ perl -e 'while(<>){s/^/$ARGV:/; print;}' file*
    file1:hello1
    file2:hello2
    file3:hello3