I have no problems with the anonymous sub. I do take issue, though, with the list of scalars for options. I much prefer to use a hash to keep things in one place.

But hang on! If you mispell a scalar, the compiler will bark at you. If you mispell a hash key, the runtime will autovivify it for you. Hmm.

But that's ok too, because what I really prefer doing is hiding it all away in a scope, and declaring subs as The Only Way of retrieving values. Admittedly, you still don't get a compile time error, but it will blow up at runtime if you get things worng. My template looks something like:

{ use Getopt::Long; my %opt; GetOptions ( \%opt, qw/ verbose! file:s debug+ help/ ) || die sub { print <<END_OF_HELP; $0: you blew it! Switches are as follows: --help | -h this help screen ... END_OF_HELP } sub debug { exists $opt{debug} ? $opt{debug} : 0 } sub verbose { exists $opt{verbose} ? 1 : 0 } sub file { if( not exists $opt{f} ) { '' } elsif( not defined $opt{f} ) { '/etc/passwd' } else { $opt{f} } } }

The sub file lets you distinguish between an argument that is absent (return an empty string), present, but with no value (return a fixed name) or present with a value (return the value).

Since the %opt hash isn't available outside the scope, the program can't (accidentally or on purpose) modify the contents. This may be construed as a feature.

- another intruder with the mooring of the heat of the Perl


In reply to Re: Getopt::Long good style? (tight scoping) by grinder
in thread Getopt::Long good style? by Skeeve

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.