jaa has asked for the wisdom of the Perl Monks concerning the following question:

I have read this question in the FAQ, and also looked through perldata.

I often use this for named parameters:

sub abc { my %param = @_; for my $required qw( banana nut ) { die "missing: $required" unless defined $param{$required}; } # etc }
Now, what I would like to do is something like:
sub abc { # set up defaults my %param = ( apples => 'green', banana => 'yellow', ); # now override with any passed params %param = @_; for my $required qw( banana nut ) { die "missing: $required" unless defined $param{$required}; } # etc }

but the @_ assignment to %param trashes any existing values. I already know I can

my %passed = @_; (@param{ keys %passed }) = values %passed;

but is there a way to do it without an intermediate hash? i.e. straignt from @_? I want something like push that works on a hash?

Hope this makes sense! Thanks in advance,

Jeff

Replies are listed 'Best First'.
Re: How do I push values onto an existing hash?
by broquaint (Abbot) on Jul 10, 2003 at 10:27 UTC
    There are a few ways to do this the simplest being
    %params = ( %params, @_ );
    Or you could intermediary anonymous hashes e.g
    @params{ keys %{ {@_} } } = values %{ {@_} };
    But using an intermediary named hash is probably the easiest to follow.
    HTH

    _________
    broquaint

Re: How do I push values onto an existing hash?
by Zaxo (Archbishop) on Jul 10, 2003 at 10:29 UTC

    Here's one way,

    my %param = ( apples => 'green', banana => 'yellow', @_ );
    Since you have a default for the banana key, you shouldn't need to check its existence.

    After Compline,
    Zaxo

      > don't have to test the banana

      unless of course I called it with

      abc( banana => undef, eat => 'mon' ); sub abc { my %param = ( apples => 'green', banana => 'yellow', @_ ); # now just have to figure out the 'mon' key... # and the banana colour! }
      Thanks for both suggestions! doh! 8-)