in reply to Duplicating Pascal's with statement in Perl for anonymous data structures
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Duplicating Pascal's with statement in Perl for anonymous data structures
by Tanktalus (Canon) on Mar 28, 2005 at 18:49 UTC | |
|
Re^2: Duplicating Pascal's with statement in Perl for anonymous data structures
by Roy Johnson (Monsignor) on Mar 28, 2005 at 19:12 UTC | |
by ambrus (Abbot) on Mar 28, 2005 at 19:16 UTC | |
by Roy Johnson (Monsignor) on Mar 28, 2005 at 19:50 UTC |