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

Greetings, monks I found myself wondering what would be the nicest way to parse commandline arguments. Previously i was using something like this:
for($i=0; $i<@ARGV; $i+=2) { $ip = $ARGV[$i+1] if $ARGV[$i] eq '-i' || $ARGV[$i] eq '--ip'; $port = $ARGV[$i+1] if $ARGV[$i] eq '-p' || $ARGV[$i] eq '--port'; }
Much like one would do it in c. Now i found this way, which is much nicer:
while(@ARGV) { $_ = shift @ARGV; $ip = shift @ARGV if /-i/ || /--ip/; $port = shift @ARGV if /-p/ || /--port/; }
Note that i expected shift @ARGV would work. Oh well. How would you do it? Thanks for your wisdom :-)

Replies are listed 'Best First'.
Re: parsing commandline arguments
by djantzen (Priest) on Feb 12, 2002 at 13:37 UTC

    Well, you can certainly do it this way if you want, however you'll find it much nicer to use Getopt::Long.

Re: parsing commandline arguments
by dreadpiratepeter (Priest) on Feb 12, 2002 at 14:22 UTC
    You also might want to look at Getopt::Declare by Damian Conway. It is the kitchen-sink of argument processors. It support any number of argument formats, automatically generates usage, can verify multi-argument dependencies, plus a whole lot more.

    -pete
    Entropy is not what is used to be.
Re: parsing commandline arguments
by grinder (Bishop) on Feb 12, 2002 at 16:28 UTC

    You may wish to consider reading my Tutorial on the subject, which has nearly the same title :)

    Parsing your script's command line

    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'
Re: parsing commandline arguments
by jonjacobmoon (Pilgrim) on Feb 12, 2002 at 14:24 UTC
    Just a good rule thumb:

    If you know that its been done, and is being done often, check for a module. As fever said, Getopts applies here, but you never want to waste time writting code that has already been written.


    I admit it, I am Paco.
Re: parsing commandline arguments
by io (Scribe) on Feb 12, 2002 at 21:42 UTC
    Thanks very much for your suggestions. The tutorial is very helpfull :-)
Re: parsing commandline arguments
by pizza_milkshake (Monk) on Feb 12, 2002 at 14:23 UTC
    at the risk of being more confusing (as well as leaving out strict and my), I offer this:
    while(@ARGV){
            ($_, $v) = splice @ARGV, -2;
            $ip = $v if /--?ip?/;
            $port = $v if /--?p(ort)?/
    }