white-fox has asked for the wisdom of the Perl Monks concerning the following question:

hello monks.....
how can i add option to my command program perl....
i mean.....for example if user type "My_progname -v" then type version of my program....or if type "My_progname -h" then type help of my program....
i use this code...but it gives me a error if i don't use option

#!/usr/bin/perl -w use strict; use warnings; sub version { print "Beginning perl's \"Hello, World.\" version 2.0\n"; } my $option = shift; version if $option eq "-v" or $option eq "--version"; print "Hello, World.\n";

Replies are listed 'Best First'.
Re: how add option to my program?
by Joost (Canon) on Mar 26, 2005 at 19:38 UTC
Re: how add option to my program?
by ambs (Pilgrim) on Mar 26, 2005 at 19:49 UTC
    For simple switches (with only one - before the switch) you can use
    #!/usr/bin/perl -s
    
    When you call this script with a swtich (say, -foo) the $foo variable gets defined. If you use it with a value (say, -foo=bar) then $foo will get the 'bar' value.

    It is not so powerfull as getopt, but is useful for small tasks.

    Alberto Simões

Re: how add option to my program?
by graff (Chancellor) on Mar 27, 2005 at 05:36 UTC
    ...but it gives me a error if i don't use option

    As others have said, GetOpt (Standard or Long) is a good thing to learn, but sometimes, when doing something quick and easy, I just work directly with @ARGV; if all you want is a "-v" or "--version" option, then here's a way to avoid the warning about "uninitialized value in string eq" (which is not an error -- just a warning, because you've asked for warnings):

    sub version { print "whatever\n"; } version if ( @ARGV and shift =~ /^--?v(?:ersion)?$/ ); # ...
    Of course, when you need a script to handle multiple options (and especially if you might add more to it as time goes by), you'll want to spend the time to learn one of the Getopt modules. If you don't, you'll be spending about the same amount of time writing a while loop with lots of "if ... elsif ... else ..." stuff for each new script that uses multiple options.

    BTW, I think having both "-w" and "use warnings" is redundant. The "perllexwarn" man page describes the latter as a replacement for the former.

Re: how add option to my program?
by chas (Priest) on Mar 26, 2005 at 19:50 UTC
    You can change your code to:
    use strict; use warnings; sub version { print "Beginning perl's \"Hello, World.\" version 2.0\n"; } my $option = shift; $option or $option = ""; version if $option eq "-v" or $option eq "--version"; print "Hello, World.\n";
    This eliminates the uninitialized value error. However, you still get "Hello, World" even with an option; I'm not sure if that's what you want...
    Getopt is likely the way to go (much more flexibility.)
    chas