I want to parse a list of arguments in a perl script, for example i have this situation :
script.pl -h 127.0.0.1 -u user -p pass arg1 arg2 arg3
How can i do for parse the list of argument that aren't option in an array, and the option parameter in scalar value ?
Thanks.
Well, if they are the only things on the command line that aren't given as options, then they should still be in @ARGV
. So just use @ARGV
.
use Getopt::Long;
# save arguments following -h or --host in the scalar $host
# the '=s' means that an argument follows the option
# they can follow by a space or '=' ( --host=127.0.0.1 )
GetOptions( 'host=s' => \my $host
, 'user=s' => \my $user # same for --user or -u
, 'pass=s' => \my $pass # same for --pass or -p
);
# @ARGV: [ qw<arg1 arg2 arg3> ]
see Getopt::Long
The arguments to your program are stored in @ARGV
.
If you want to do any handling of switches at all, please use Getopt::Long
, which is a standard Perl module.
Even if you think "Oh, I can just pick the stuff I want out of the list", please use Getopt::Long
, because I guarantee you the time will come that you will add more switches, and you will wind up saying "Man, I wish I'd started using Getopt::Long from the beginning."
Please also see my blog post "Use Getopt::Long even if you think you don't need it".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With