Search code examples
perlcommand-line-argumentsgetopt-long

How to verify which flags were read using Getopt::Long in Perl?


myscript.pl

my $R;
my $f1 = "f1.log";
my $f2 = "f2.log";
my $f3 = "f3.log";

sub checkflags {

    GetOptions('a=s'    => \$f1,
               'b=s'    => \$f2,
               'c=s'    => \$f3,
    );

    open $R, '>', $f1 or die "Cannot open file\n"; # Line a
}
  • All the flags are optional.

  • If I call the script as

    perl myscript.pl -a=filename
    

    I need to append a .log to the filename before opening it at Line a.

  • For that I need to know whether GetOptions read something into $f1 or not.

How can this be done?


Solution

  • The simplest solution is to look for /[.]log$/ in $f1 and add it if it isn't present. Unfortunately that means that when the user passes in "foo.log" and wanted it to become "foo.log.log" it won't, but I think we can agree that user is a jerk.

    A better option, that will make the jerk happy, is:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Getopt::Long;
    
    GetOptions(
        'a=s'    => \my $f1,
        'b=s'    => \my $f2,
        'c=s'    => \my $f3,
    );
    
    if (defined $f1) {
        $f1 .= ".log";
    } else {
        $f1 = "f1.log";
    }
    
    print "$f1\n";
    

    If you want to define all of default names at the top, use a different variable to do that (it is probably better reading code anyway):

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use Getopt::Long;
    
    my $default_f1 = "f1.log";
    my $default_f2 = "f2.log";
    my $default_f3 = "f3.log";
    
    GetOptions(
        'a=s'    => \my $f1,
        'b=s'    => \my $f2,
        'c=s'    => \my $f3,
    );
    
    if (defined $f1) {
        $f1 .= ".log";
    } else {
        $f1 = $default_f1;
    }
    
    print "$f1\n";