in reply to Hash multiple initialization

New hash:

my %hash = ( ( map { $_=>'toto' } qw( a b c f t u ) ), ( map { $_=>'titi' } qw( b g k p ) ), );

Existing hash:

$hash{$_} = 'toto' for qw( a b c f t u ); $hash{$_} = 'titi' for qw( b g k p );

You have "b" twice, which means one (the earlier one) will get erased.

Replies are listed 'Best First'.
Re^2: Hash multiple initialization
by AnomalousMonk (Archbishop) on Oct 08, 2008 at 20:13 UTC
    Might this be a case in which prototyping is actually useful as a syntactic sweetener?

    sub mass_init (\%\@$); my @init_to_toto = qw{ a b c f t u }; my %hash = ( y => 'pre', z => 'pre', ); mass_init(%hash, @init_to_toto, 'toto'); mass_init(%hash, @{[ qw(b g k p) ]}, 'TITI'); use Data::Dumper; print Dumper \%hash; sub mass_init (\%\@$) { my ($hashref, $arrayref, $string) = @_; # $hashref->{$_} = $string for @$arrayref; @{ %$hashref }{ @$arrayref } = ($string) x @$arrayref; }
    Output:
    $VAR1 = { 'a' => 'toto', 'y' => 'pre', 'p' => 'TITI', 'c' => 'toto', 'u' => 'toto', 'k' => 'TITI', 'g' => 'TITI', 'b' => 'TITI', 'z' => 'pre', 'f' => 'toto', 't' => 'toto' };
      I don't see the point of the prototype. It actually makes your example caller bigger!
      my @init_to_toto = qw{ a b c f t u }; my %hash = ( y => 'pre', z => 'pre', ); mass_init(\%hash, \@init_to_toto, 'toto'); mass_init(\%hash, [qw( b g k p )], 'TITI'); use Data::Dumper; print Dumper \%hash; sub mass_init { my ($hashref, $arrayref, $string) = @_; # $hashref->{$_} = $string for @$arrayref; @{ %$hashref }{ @$arrayref } = ($string) x @$arrayref; }