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

I stumbled across this feature of getopts in

Re: Beginners guide to File::Find

Basically @ARGV > 0 and getopts('a:', \my %opt) or die << "USAGE";

works, but "my" instead of "\my" doesn't work. And fwiw, neigher does {my %opt}.

What's up with that? What is that backslash doing? And is there some less arcane way to parse args, with Getopts::Std or one of the other arg handling modules?

Thanks!

Edited by planetscape - linkified link

Replies are listed 'Best First'.
Re: Why do I need a slash before my -- \my -- in getopts
by Fletch (Bishop) on Apr 12, 2006 at 13:31 UTC

    The backslash is taking a reference to %opt (so getopts recieves a hashref which it populates). It's no different than

    my %opt; @ARGV > 0 and getopts( 'a:', \%opt ) or die <<"USAGE";

    or

    my $opt = {}; @ARGV > 0 and getopts( 'a:', $opt ) or die <<"USAGE";

    Just looks a little funy. And I usually use Getopt::Long, but that's just me (actually recently I use this more often, but that's not really going to help you . . . :).

Re: Why do I need a slash before my -- \my -- in getopts
by ikegami (Patriarch) on Apr 12, 2006 at 16:23 UTC
    First, a primer

    { ... } creates a new (anonymous) hash. The hash is initialized using the specified list. A reference to the new hash is returned.

    \%hash simply returns a reference to the specified hash.

    Now, in context

    { my %opts } first creates hash %opts. Then it creates a new (anonymous) hash. The anonymous hash is initialized with the contents of %opts (which is empty). A reference to the anonymous hash is returned (and passed to getopts).

    That doesn't work because getopts populates the anonymous hash, which is freed as soon as getopts returns because you never saved a reference to it. And %opts is left untouched because getopts doesn't know it exists.

    When you use \%opts, on the other hand, you pass a reference to %opts, so getopts populates %opts

    Fletch covered the role of my in his post.