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

I'm having some trouble trying to use getopt. Here's what my code looks like:
use Getopt::Std; use strict; my $opt_i; getopt('i'); print "Increment value is $opt_i\n";
But when I run the program with script.pl -i 2, $opt_i doesn't have a value. What am I doing wrong? Thanks.

Replies are listed 'Best First'.
Re: Using getopt
by grep (Monsignor) on Jan 24, 2002 at 04:37 UTC
    Your lexical 'my $opt_i' is masking the package $opt_i that Getopt::Std creates.

    Use
    use Getopt::Std; use strict; use vars qw/$opt_i/; getopt('i'); print "Increment value is $opt_i\n";


    grep
    grep> cd pub
    grep> more beer
      Thanks for the replies. That works for me now.

      This is getting off the subject, but what exactly is the difference between 'my $opt_i' and the use vars way? And could you point me to where I can read about 'lexical scope' and 'packages'?

      Thanks again.

        Dominus has an excellent article called Coping with Scoping that should help you out. Chapter 5 of the Camel and chapter 6 of the Panther are also relevant.

        --
        :wq
Re: Using getopt
by impossiblerobot (Deacon) on Jan 24, 2002 at 07:00 UTC
    Using the two-argument form of 'getopt' (passing a hash reference) allows you to avoid the global variable:
    use Getopt::Std; use strict; my %opt; getopt('i', \%opt); print "Increment value is $opt{i}\n";
    I also prefer to use 'getopts' over 'getopt' since it requires you to list all valid options, and specify whether each option takes an argument (such as your increment value).

    Impossible Robot
Re: Using getopt
by FoxtrotUniform (Prior) on Jan 24, 2002 at 04:35 UTC

    The problem is that $opt_i here is lexically scoped. Try use vars qw($opt_i); instead of my $opt_i;.

    --
    :wq
Re: Using getopt
by grep (Monsignor) on Jan 24, 2002 at 05:12 UTC
    Ovid has a excellent explaination of varible types in 'our' is not 'my' else the "Camel Book" formerly known as Programming Perl will help you.

    grep
    grep> cd pub
    grep> more beer