Search code examples
perlcommand-linegetopt

How to pass a file using GetOpt


I have a program where I need to pass a filename (and location) to the program. How can I do this? I have read the GetOpt doc so please don't point me there. My command line is as follows:

perl myprogram.pl -input C:\inputfilelocation -output C:\outputfilelocation

My GetOptions look like this:

GetOptions('input=s' => \$input,'output=s' => \$output);

Basically I need to figure out how to access that file in a while loop that I have which iterates over the lines in the file and puts each into $_

while ($input) {

...doesn't work. Note that before my file worked fine with:

open my $error_fh, '<', 'error_log';
while (<$error_fh>) { 

Solution

  • This works for me. Your GetOptions seems correct. Open file and read from the filehandle, and don't forget to check for errors:

    use warnings;
    use strict;
    use Getopt::Long;
    
    my ($input, $output);
    GetOptions('input=s' => \$input,'output=s' => \$output) or die;
    
    open my $fh, '<', $input or die;
    
    while ( <$fh> ) { 
        ## Process file.
    }