Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Getopt::Long good style? (tight scoping)

by grinder (Bishop)
on Jul 28, 2004 at 13:17 UTC ( #378024=note: print w/replies, xml ) Need Help??

in reply to Getopt::Long good style?

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://378024]
[Corion]: LanX: Yes, that's the main problem - you have lots (and lots) of workarounds in various places and stages of the processing, and to clean that mess up requires action across the complete codebase. And it's almost impossible to do it piece-by-piece

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (13)
As of 2017-01-16 14:08 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (150 votes). Check out past polls.