Search code examples
perlgetoptgetopt-long

How to use GetOptions to detect trailing strings?


I am absolutely new to Perl and I am trying to figure out a problem with Perl script parsing script arguments.

I have the following Perl script called sample-perl.pl:

use strict;
use warnings;
use 5.010;
use Getopt::Long qw(GetOptions);

my $source_address;
my $dest_address;

GetOptions('from=s' => \$source_address,
           'to=s' => \$dest_address) or die "Usage: $0 --from NAME --to NAME\n";
if ($source_address) {
    say $source_address;
}

if ($dest_address) {
    say $dest_address;
}

And if I use a command like (where I forgot to enter the second option):

perl sample-perl.pl --from nyc lon
Output will be: nyc

How can I enforce that if there is an additional string at the end, it is detected and an error is displayed instead?

Solution:

adding this will help my case at least:

if(@ARGV){
    //throw error
}

Solution

  • After calling GetOptions, check for any remaining command line options in the @ARGV array. This assumes that all unexpected arguments will generate an error:

    use strict;
    use warnings;
    use 5.010;
    use Getopt::Long qw(GetOptions);
    
    my $source_address;
    my $dest_address;
    
    GetOptions('from=s' => \$source_address,
               'to=s' => \$dest_address) or die "Usage: $0 --from NAME --to NAME\n";
    
    @ARGV and die "Error: unexpected args: @ARGV";
    
    if ($source_address) {
        say $source_address;
    }
    
    if ($dest_address) {
        say $dest_address;
    }