http://www.perlmonks.org?node_id=998761

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

Hello Monks,


I'm not sure what's going on here with this. I've used this method for command line args over and over again
and suddenly now it doesn't seem to be working correctly...?

I'm simply passing in 2 IP Addresses to the script but they are not being assigned to the Variables and
I can't seem to figure out why...


COMMAND:
./test_perl.pl ipAddr=192.168.1.1 server=192.168.5.1

CODE:
#!/usr/bin/perl use warnings; use strict; use File::Copy; use Getopt::Long; use Term::ANSIColor qw(:constants); $Term::ANSIColor::AUTORESET = 1; # TEST --> Print the Args so we can see that they are being passed: print "\@ARGV: \"@ARGV\"\n\n"; my $srv_address; my $ip_address; if ( @ARGV > 0 ) { print "GETTING OPTIONS...\n\n"; GetOptions('ipAddr=s' => \$ip_address, 'server=s' => \$srv_address ); } print BOLD " IP Address = " . RESET "$ip_address\n"; print BOLD "SERVER Address = " . RESET "$srv_address\n"; exit 0;


OUTPUT:
@ARGV: "ipAddr=192.168.5.196 server=192.168.5.1" GETTING OPTIONS... Use of uninitialized value $ip_address in concatenation (.) or string +at ./test_diff.pl line 25. IP Address = Use of uninitialized value $srv_address in concatenation (.) or string + at ./test_diff.pl line 26. SRV Address =


Does anyone see what I'm doing wrong here...?
Any thoughts would be great!



Thanks in Advance,
Matt


Replies are listed 'Best First'.
Re: GetOptions Function NOT Assign CLI Args to Variables?
by frozenwithjoy (Priest) on Oct 12, 2012 at 18:08 UTC

    You need to tell Getopt what options your are assigning using single or double dashes (-option or --option). Run it like this:

    ./test_perl.pl --ipAddr 192.168.1.1 --server 192.168.5.1

    The output I get from running it this way:

    @ARGV: "--ipAddr 192.168.1.1 --server 192.168.5.1" GETTING OPTIONS... IP Address = 192.168.1.1 SERVER Address = 192.168.5.1
Re: GetOptions Function NOT Assign CLI Args to Variables?
by toolic (Bishop) on Oct 12, 2012 at 18:40 UTC
    Unrelated to your problem... there is no need to check @ARGV before calling GetOptions. The function does that checking for you, and it also modifies @ARGV if there are options.
Re: GetOptions Function NOT Assign CLI Args to Variables?
by mmartin (Monk) on Oct 12, 2012 at 18:55 UTC
    Hey frozenwithjoy, thanks for the reply!

    Ughhhh... Haha thanks, I knew it had to be something little I was missing...!
    Thanks for that!



    Hey toolic, thanks for the reply!

    Yea, I didn't have that in there originally, but I did put it in there to try and figure out
    what the heck was going on there. So basically I just had it there for testing this problem I
    was having... But thanks for the info..!



    Thanks Again, Guys!
    Matt