Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass Getopt::Long options to a subroutine that's also an option?

I am trying to setup Getopt::Long to handle the arguments from a configuration script.

Here is my starter:

#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;

my $config_file = '';

GetOptions (    
    'config|c=s' => \$config_file,
    'add|a' => \&add_server,
    'del|d' => \&del_server,        
);

sub add_server {    
    print "$config_file\n";    
}

sub del_server {    
    # Left blank for now.    
}

The odd thing is I am running into a problem when I run my script with something like this:

./config.pl -a -c config.xml

It does NOT print the -c option, but if I run it like this,

./config.pl -c config.xml -a

it works like it should.

I think I understand the reason why; it has to do with the order execution right?

How can I fix it? Should I use Getopt::Long in conjunction with @ARGV?

Ultimately, I am trying to make the command line args pass into the subroutine that I am calling. So if -a or --add, I want the options of -c or --config to pass into the subroutine when it is called.

Any ideas?

like image 974
ianc1215 Avatar asked Dec 07 '25 20:12

ianc1215


1 Answers

I don't see the need to call the subroutine directly from the GetOptions call. Control the order like this:

use strict;
use warnings;
use Getopt::Long;

my %opts = (config => '');

GetOptions(\%opts, qw(
   config|c=s
   add|a
   del|d
));

add_server() if $opts{add};
del_server() if $opts{del};

sub add_server {    
    print "$opts{config}\n";
}

sub del_server {}
like image 163
toolic Avatar answered Dec 09 '25 17:12

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!