Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse command line arguments?

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.

like image 222
aleroot Avatar asked Oct 19 '10 21:10

aleroot


2 Answers

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

like image 131
Axeman Avatar answered Oct 04 '22 21:10

Axeman


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".

like image 29
Andy Lester Avatar answered Oct 04 '22 21:10

Andy Lester