in reply to Default named params with an embedded hash

A bit of searching brings up Hash::Merge as a fairly good bet. Alternatives: Hash::Merge::Simple, Data::Merger, Data::Overlay (the latter two don't have reviews so I'm not sure), or roll your own (see also this PerlMonks post).

  • Comment on Re: Default named params with an embedded hash

Replies are listed 'Best First'.
Re^2: Default named params with an embedded hash
by Athanasius (Archbishop) on Aug 29, 2014 at 02:44 UTC

    Thanks for this. I wasn’t familiar with the Hash::Merge module, it’s a useful addition to the toolbox.

    In case it helps anyone else, here’s how I got it to work with the OP’s script:

    #! perl use strict; use warnings; use feature 'say'; use Data::Dump 'pp'; use Hash::Merge 'merge'; my %valid_inputs = ( one => 1, two => 2, ); validate( valid_inputs => \%valid_inputs, max_record_length => 72, ); sub validate { my %params = ( valid_inputs => { one => 'one', two => 'two', three => 'three', four => 'four', }, max_record_length => 24, ); Hash::Merge::set_behavior('RIGHT_PRECEDENT'); %params = %{ merge( \%params, { @_ } ) }; say "\%params =\n", pp(\%params); }

    (The only slightly tricky part was turning @_ into a hash reference.) Output:

    12:41 >perl 987_SoPW.pl %params = { max_record_length => 72, valid_inputs => { four => "four", one => 1, three => "three", t +wo => 2 }, } 12:42 >

    I’d call that elegant.

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,