Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

beautifying Getopt::Long in situ subs

by perlcapt (Pilgrim)
on Apr 02, 2006 at 13:46 UTC ( #540748=perlquestion: print w/replies, xml ) Need Help??
perlcapt has asked for the wisdom of the Perl Monks concerning the following question:

I'm looking for suggestions on how to beautify/clean_up my subroutine argument references. Here is the situation: I have many options to my application, all of which are stored in an object attributes structure. Typical Getopt::Long elements looks like this:
my $opts = GetOptions ( "input|source|i:s" => sub { if($_[1]) { $new->source($_[1]); }else{ $new->source($last->source); } }, "verbose" => sub { $new->verbose($_[1]); }, # and so on
What I find ugly is the use of $_[1] to reference the value that GetOptions parses for each option. $_[0] is the option name. $_[1,2] are used for values or references to hashes and lists. I suppose I could just pass the whole list to the object method, but that gets ugly since most of these methods are designed to store/retrieve attributes and defined by an AUTOLOAD subroutine down in the class i.e. package.
Updated to reflect proper variable prefix for list refs. thanks to davido for waking me up about my syntax. -ben

Replies are listed 'Best First'.
Re: beautifying Getopt::Long in situ subs
by davido (Archbishop) on Apr 02, 2006 at 17:05 UTC

    First, turn on warnings and behold what happens. What you're doing works, but is not proper. Change all occurrences of @_[1] to $_[1] (and so on).

    Also, with constants you could name the subscripts instead. Example:

    use constant OPTION_NAME => 0; sub { if( $_[OPTION_NAME] ) { .......


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://540748]
Approved by wfsp
[ambrus]: As for TeX, I'm not trying to discourage anyone from writing carefully beautifully typeset documents, in maths or outside. But most people aren't willing to do that, and will spend only little time about the formatting,
[ambrus]: and try to leave everything else to automated systems without checking how what they write came out format-wise, and for those people, discounting the part about journals with a specific format above,
[ambrus]: just blindly recommending to use LaTeX is a bad idea now.
[Discipulus]: I havery limited needs in such field. Sometimes (for children party invitations) i draw something by hand and I scan it to include into an ms doc.

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2017-09-26 11:22 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (293 votes). Check out past polls.