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

Re: generic getopt to hash

by bv (Friar)
on Oct 01, 2009 at 17:46 UTC ( [id://798698]=note: print w/replies, xml ) Need Help??


in reply to generic getopt to hash

But of course! Otherwise, how does it know that --name needs a value? or that --list takes more than one value? This is the way the getopt libraries work. If you want different, you will likely have to write your own. Simply, it might look like this:

sub magic_opts { my ($lastopt,%opthash); for (split) { if (/^-+(.*)/) { $lastopt=$1; $opthash{$lastopt}=[]; } else { push @{$opthash{$lastopt}}, $_; } } return \%opthash; }

Of course this code is buggy, specifically it does not handle the case if there was no previous --option. Good luck!

print pack("A25",pack("V*",map{1919242272+$_}(34481450,-49737472,6228,0,-285028276,6979,-1380265972)))

Replies are listed 'Best First'.
Re^2: generic getopt to hash
by ikegami (Patriarch) on Oct 01, 2009 at 18:41 UTC

    You code doesn't allow for parameters that aren't options. Let's introduce --. And let's handle the case with no previous --option. Then you can do

    command --option ... -- file1 file2
    sub parse_args { my $last_opt = ''; my %opts; while (@ARGV) { my $arg = shift(@ARGV); if ($arg eq '--') { last; } elsif ($arg =~ s/^--?//) { $opts{$last_opt = $arg} = []; } else { push @{ $opts{$last_opt} }, $arg; } } unshift @ARGV, @{ delete $opts{''} } if $opts{''}; return \%opts; }

    Supporting val=0 as an option makes no sense. It would prevent you from having values with equal signs in them.

    If -list a b c wasn't supported, we could do away with requiring --.

Re^2: generic getopt to hash
by Anonymous Monk on Oct 01, 2009 at 19:56 UTC
    That's what I was looking for. Thanks.

    I've tweaked one line though:

    $opthash{$lastopt}=[] unless ref $opthash{$lastopt};

    So that it can handle both types of lists:

    script.pl --list aa --list bb and script.pl --list aa bb

    cheers

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-20 03:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found