Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

(jcwren) Re: getopts and ARGV

by jcwren (Prior)
on May 27, 2002 at 21:47 UTC ( #169650=note: print w/ replies, xml ) Need Help??


in reply to getopts and ARGV

Although seemingly undocumented, getopts() stops parsing as soon as it hits a non-switch formatted argument (an argument that doesn't have a leading dash) in the command line that doesn't have a preceeding switch that accepts a parameter.

Assuming you have getopts (":abcd:e:"), the following cases apply:

perl test.pl -a -d 5

getopts() returns a non-zero value, the hash contains -a=1, -d=5, and @ARGV is 0 length.

perl test.pl -a -u -d 5

getopts() returns a zero value, the hash contains -a=1, -d=5, and @ARGV is 0 length.. A warning is also printed from inside getopts()

perl test.pl -a xxx -d 5

returns a zero value, the hash contains -a=1, and @ARGV contains 'xxx', '-d', '5'

You can use the fact that @ARGV still contains values to print an error message. Or, you could get more sophisticated, and do something with the unparsed argument. Since the arguments are dropped from @ARGV as they are parsed, you could stay in a loop until @ARGV is 0, print "I don't recognize this argument: $@ARGV[0]\n", shift @ARGV, and call getopts() again. This will result in your hash containing all the valid arguments that were on the command line, and personalized messages for ones that are invalid.

--Chris

e-mail jcwren


Comment on (jcwren) Re: getopts and ARGV
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://169650]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2015-07-02 04:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (27 votes), past polls