dukea2006 has asked for the wisdom of the Perl Monks concerning the following question:

Total Newbie Question: How do I pass a file name as a command line argument? I am currently successfully passing the file name in the Open function:

#!/usr/bin/perl use warnings; use strict; open(FILE1,"testData.txt ")or die ("Unable to open the file.");

The above code works great - I can open the file load the data into an array and I'm good to go. The only issue is every time I want execute it against a different data file, I have to edit my Perl code. I'd rather pass the file name at the command line to make things more dynamic.

Again, this feels like a total newbie question (probably because that is my current skill level) but I haven't been able to find much on how to accomplish this. I read through the input \ output tutorials and I'm still in need of help.

Thanks!

Replies are listed 'Best First'.
Re: Opening a File from the Command Line
by almut (Canon) on Apr 06, 2010 at 21:11 UTC

    See @ARGV.

    For example:

    #!/usr/bin/perl use warnings; use strict; my $filename = shift @ARGV; open(FILE1, "<", $filename) or die "Unable to open '$filename': $!";
Re: Opening a File from the Command Line
by FunkyMonk (Bishop) on Apr 06, 2010 at 21:15 UTC
    Command line arguments are passed in to the program using a special array. See @ARGV in perlvar. Or, you may play with code something like:

    #cli.pl print "$_: $ARGV[$_]\n" for 0..$#ARGV;

    $ perl cli.pl one two three 0: one 1: two 2: three

    If you want to use a more sophisticated command line, look at Getopt::Long.

Re: Opening a File from the Command Line
by 7stud (Deacon) on Apr 06, 2010 at 21:57 UTC
    You may also see something like this:

    while (<>) {

    That thing -> <> is called the 'diamond operator', and it assumes all the words entered on the command line are file names. It then combines all the files into one big file and reads one line at a time.

      [the diamond operator] assumes all the words entered on the command line are file names
      No it doesn't. The diamond operator will read from all the elements of @ARGV as if they are files. That may, or may not, be the same as the command line arguments.
      It then combines all the files into one big file
      No, it doesn't do that either. It reads each file line by line, setting $ARGV to the name of the file currently being read.

      See I/O operators for <>, @ARGV and $ARGV for further reading.