in reply to How to process named parameters that have the same key name?

Based on saintmike's code - here is one way to move the "HoA when necessary" complexity to the CALLED subroutine:
use Data::Dumper; use strict; use warnings; simple_call( animal => 'monkey', fish => 'tuna', insect => 'ant', insect => 'spider' ); ########################## sub simple_call { my %params; while(my($key, $value) = splice @_, 0, 2) { if (exists $params{$key}){ if (ref $params{$key} eq "ARRAY"){ push @{$params{$key}},$value; }else{ $params{$key} = [$params{$key},$value]; } }else{ $params{$key} = $value; } } print Dumper \%params; }
prints
$VAR1 = { 'insect' => [ 'ant', 'spider' ], 'animal' => 'monkey', 'fish' => 'tuna' };
Update:Corrected attribution to saintmike, and deleted unnecessary @params declaration.

     "Man cannot live by bread alone...
         He'd better have some goat cheese and wine to go with it!"

Replies are listed 'Best First'.
Re^2: How to process named parameters that have the same key name?
by maard (Pilgrim) on Oct 19, 2005 at 10:58 UTC
    $VAR1 = { 'insect' => [ 'ant', 'spider' ], 'animal' => 'monkey', 'fish' => 'tuna' };
    If duplication is allowed, then it would be better to construct HoA, where values are always arrays to simplify further walking through such structure.
    $VAR1 = { 'insect' => [ 'ant', 'spider' ], 'animal' => ['monkey'], 'fish' => ['tuna'] };