How about:
sub with(\%$) { my ($hash, $values) = @_; $hash->{$_} = $values->{$_} foreach keys %$values; } $anonhash = { id => 'u1234', }; with %$anonhash, { name => 'dave', city => 'San Francisco', phone => '555-1212', hobbies => [ qw( Perl Anime ) ], }; require Data::Dumper; print(Data::Dumper::Dumper($anonhash)); __END__ $VAR1 = { 'id' => 'u1234', 'name' => 'dave' 'city' => 'San Francisco', 'phone' => '555-1212', 'hobbies' => [ 'Perl', 'Anime' ], };
With a slight change, you could keep the word "do" (as seen behind the cut), but it's less efficient (because the new values are passed as a list instead of as a hash ref).
sub with(\%%) { my ($hash, %values) = @_; $hash->{$_} = $values{$_} foreach keys %values; } $anonhash = { id => 'u1234', }; with %$anonhash, do { name => 'dave', city => 'San Francisco', phone => '555-1212', hobbies => [ qw( Perl Anime ) ], }; require Data::Dumper; print(Data::Dumper::Dumper($anonhash)); __END__ $VAR1 = { 'id' => 'u1234', 'name' => 'dave' 'city' => 'San Francisco', 'phone' => '555-1212', 'hobbies' => [ 'Perl', 'Anime' ], };
Update: Fixed the error pointed out by Tanktalus.
In reply to Re: Duplicating Pascal's with statement in Perl for anonymous data structures
by ikegami
in thread Duplicating Pascal's with statement in Perl for anonymous data structures
by Popcorn Dave
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |