in reply to Getting commandline params

Here is the difference between the getopt() method and the getopts() method.

getopt()

C:\>type getopt.pl use Getopt::Std; our($opt_p); getopt('p'); print "Using the getopt() method \$opt_p is "; print defined $opt_p ? "'$opt_p'" : "undefined"; C:\>perl getopt.pl Using the getopt() method $opt_p is undefined C:\>perl getopt.pl -p Using the getopt() method $opt_p is undefined C:\>perl getopt.pl -p123 Using the getopt() method $opt_p is '123'

getopts() with an s!

C:\>type getopts.pl use Getopt::Std; our($opt_p); getopts('p'); print "Using the getopts() method \$opt_p is "; print defined $opt_p ? "'$opt_p'" : "undefined"; C:\>perl getopts.pl Using the getopts() method $opt_p is undefined C:\>perl getopts.pl -p Using the getopts() method $opt_p is '1' C:\>perl getopts.pl -p123 Unknown option: 1 Unknown option: 2 Unknown option: 3 Using the getopts() method $opt_p is '1' C:\>

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Replies are listed 'Best First'.
Re: Re: Getting commandline params
by Amoe (Friar) on Sep 02, 2001 at 15:33 UTC
    Okay, thanks for all the help. I'm halfway there now, I think. So if I wanted to get $switch to equal 1 if the switch was on its own and $arg to equal the argument, I should be able to this...
    use Getopt::Std; our($opt_p); getopt('p'); my $arg = $opt_p; getopts('p'); my $switch = $opt_p; print "Switch is $switch and arg is $arg\n";
    Sadly, when run:
    >perl stuff.pl Switch is and arg is # Okay so far... >perl stuff.pl -p Switch is and arg is # No, switch should equal 1... >perl stuff.pl -p http://www.proxy.com Switch is http://www.proxy.com and arg is http://www.proxy.com # Shou +ldn't switch equal 1 here too?
    So, any input on how to get the desired behaviour, or maybe I shouldn't be going about it like this anyway?

      I don't generaly use the Getopt module. I parse stuff myself to get the behaviour I want. You get the command line args in @ARGV. Here is an example with minimal flexibility and error checking. It takes a -p flag and and optional proxy arg.

      C:\>type test.pl my ($switch, $proxy) = @ARGV; $switch = ($switch eq '-p') ? 1 : 0; $proxy = defined $proxy ? $proxy : 'undef'; print "Switch is '$switch', and proxy is '$proxy'\n"; C:\>perl test.pl Switch is '0', and proxy is 'undef' C:\>perl test.pl -p Switch is '1', and proxy is 'undef' C:\>perl test.pl -p http://proxy.foo.com/proxy.pac Switch is '1', and proxy is 'http://proxy.foo.com/proxy.pac' C:\>perl test.pl http://proxy.foo.com/proxy.pac Switch is '0', and proxy is 'undef' C:\>

      cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print