Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re^3: GetOpt::Long usage style

by OneTrueDabe (Acolyte)
on May 08, 2014 at 16:00 UTC ( #1085476=note: print w/replies, xml ) Need Help??


in reply to Re: Re: GetOpt::Long usage style
in thread GetOpt::Long usage style

I know this is ancient, but since it's high on the Google hit list, I wanted to mention one thing...

This very cool trick does not work for @arrays. :-(

This:

use Getopt::Long; GetOptions( 'single=s' => \(my $single = ''), 'multi=s' => \(my @multi = ()), );
does *NOT* DWIM. According to "perlref":
As a special case, "\(@foo)" returns a list of references to the contents of @foo, not a reference to @foo itself.
I tried all kinds of permutations, and the best I could come up with was:
use Getopt::Long; GetOptions( 'single=s' => \(my $single = ''), 'multi=s' => do { use vars '@multi'; \@multi }, );
which, isn't quite as clean, IMHO.

(It *DOES*, however, keep the variable declarations and command-line options on the same line, at least, so you don't have to make changes in multiple places when adding new options. *shrug*)

Replies are listed 'Best First'.
Re^4: GetOpt::Long usage style (\my @a)
by tye (Sage) on May 09, 2014 at 00:37 UTC
    use Getopt::Long; GetOptions( 'single=s' => \(my $single = ''), 'multi=s' => \my @multi, );

    If you want to provide a non-empty default value, one way is:

    use Getopt::Long; GetOptions( 'single=s' => \(my $single = ''), 'multi=s' => grep { @$_ = ('a','b') } \my @multi, );

    - tye        

Re^4: GetOpt::Long usage style
by demerphq (Chancellor) on Apr 11, 2016 at 17:22 UTC

    Besides what tye said in Re^4: GetOpt::Long usage style (\my @a), you can just use an arrayref instead. Obviously the reference operator \ required for scalars can be omitted.

    'multi=s' => (my $multi = [1..3]),

    Same for a hash/hashref. Admittedly it is not quite the same as what one would expect from

    'multi=s' => (\my @multi = (1..3)),

    Which throws an error, which I think is arguably an error in Perl.

    BTW, sorry it took me so long to reply, and thanks for adding your point.

    ---
    $world=~s/war/peace/g

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1085476]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2019-05-22 21:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you enjoy 3D movies?



    Results (140 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!