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

My script takes options and input from a file. I try to use getopt() to read a flag but it seems to return nothing. What is my newbie mistake?

myscript.pl:

use strict; use Getopt::Std; our $opt_v; print join(':',@ARGV), "\n"; getopt('v');
displays:
$ myscript.pl -v < data.txt -v opt_v =
~Diz

Replies are listed 'Best First'.
Re: Getopt::Std and simple options
by sk (Curate) on Sep 06, 2005 at 05:26 UTC
    Are you trying to use  -v something like a verbose flag?

    You might want to use getopts() instead of getopt() as the latter requires the swtich to have an arg (i.e. you need to use it as scriptname -v somearg) getopts() provides this by : to the end of switch.

    Also you should check for return value from getopt/s(). If you had checked for the return value you would have seen  broken usage with your code as is i.e. getopt()

    use strict; use Getopt::Std; our $opt_v; # print join(':',@ARGV), "\n"; my $ret = getopts('v'); die "broken usage\n" unless $ret; print "V = ", $opt_v,$/ if defined $opt_v; __END__ V = 1
      Yes, very astute, I am trying to set a verbose flag. :)

      Thanks for your helpful reply. I should have used getopts() as getopt only takes opts with a value. I will take on board the other comments.

      ~Diz

        Checking the return value from each of the Getopt::* variants is what makes these functions really useful. An idiom that I use almost constantly for command-line tool scripts goes like this:
        my $Usage = "Usage: $0 -a [-b arg] whatever ...\n"; getopts( ... ) or die $Usage;
        When I need a reminder about the command line syntax for one of my scripts (this happens a lot), I just run it with "-?" as the only arg; since I never use "?" as an option flag, I always get the usage message.
Re: Getopt::Std and simple options
by pg (Canon) on Sep 06, 2005 at 05:12 UTC

    Your code does not really match your output. Any way, < is redirect, and does not set -v.

    use strict; use Getopt::Std; our $opt_v; getopt('v'); print $opt_v;

    When you run it as perl -w blah.pl -v abc, it prints abc as expected.

      The redirect is intentional, I included it in the example call in case that was affecting the outcome.

      I am trying to set a verbose flag '-v' with no value; that's what I meant by "simple options". The real answer was to use getopts() rather than getopt(). The code matched the output: only the script name was changed to protect the innocent. :^)

      Thanks for helping anyway.

      ~Diz