Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Help me improve this sub with named params!

by blokhead (Monsignor)
on Aug 30, 2003 at 03:56 UTC ( [id://287871]=note: print w/replies, xml ) Need Help??


in reply to Help me improve this sub with named params!

It sounds like there are only a certain number of parameters you consider "valid"... You can explicitly specify them and just ignore the rest of the hash.
my @valid = qw/buttons action foo bar xyz/; my %args = ( buttons => [], action => 'parse.cgi', @_ ); %args = map { exists $args{$_} ? $_ => $args{$_} : () } @valid; while (my ($k,$v) = each %args) { ## etc... }
This code is careful not to add additional key=>undef pairs to the hash, thus the exists check.

Alternately, you could just iterate over all valid keys and only print the ones that are available in the hash (instead of using each). This method would always print the list in a predictable order, if that's important to you:

my @valid = qw/buttons action foo bar xyz/; my %args = ( buttons => [], action => 'parse.cgi', @_ ); foreach my $k (@valid) { next if not exists $args{$k}; my $v = $args{$k}; $v = @$v if ref $v eq 'ARRAY'; print "$k => $v\n"; }

blokhead

Replies are listed 'Best First'.
Re: Re: Help me improve this sub with named params!
by BUU (Prior) on Aug 30, 2003 at 04:13 UTC
    for a slightly nicer version, what about:
    my @valid = qw/foo bar baz/; my %args=(stuff); for(@args{@valid}) { next if not defined; }
      I thought of doing something similar, but on the off chance that foobar( valid_arg => undef ); would be actually allowed I wrote what I did. Your code wouldn't be able to distinguish that call from a call that omitted the valid_arg parameter. Also, you'd have to add slightly more code to get key,value pairs (instead of just iterating over the values as you are now). But yours probably is nicer if we don't need to worry about undef parameter values.

      blokhead

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-19 00:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found