in reply to re-initialize the hash

Maybe store your defaults separately:

my %hash_defaults = ('a'=>0 , 'e'=>0 , 'i'=>0 , 'o'=>0 , 'u'=> 0,); my %hash = %hash_defaults; ... # Reinitialize %hash = %hash_defaults;

... or restructure your loop code so that the initialization and reinitialization use the same code:

while (...) { my %hash = ('a'=>0 , 'e'=>0 , 'i'=>0 , 'o'=>0 , 'u'=> 0,); ... };

... or use local (but that only works for global variables, not lexical variables):

use vars '%hash'; %hash = ('a'=>0 , 'e'=>0 , 'i'=>0 , 'o'=>0 , 'u'=> 0,); ... do { local %hash = %hash; ... make some changes }; ... changes are forgotten

Replies are listed 'Best First'.
Re^2: re-initialize the hash
by vennila (Novice) on Apr 01, 2010 at 08:38 UTC
    Hi Monks, I found the following way. Just copy the array to values of the hash which array contains the initialized values.Is it correct?
    use strict; use warnings; use Data::Dumper; my @array=(0,0,0); my %hash=('a'=>1 , 'b' =>2 , 'c'=>3,); my @values=keys%hash; @hash{@values}=@array; print Dumper \%hash;
      Yes, but unneccessarily complicated. Since you can assign a hash to an array and it will do the sensible thing, your code can be shortened to

      use strict; use warnings; use Data::Dumper; my @array=('a',0,'b',0,'c',0); my %hash=('a'=>1 , 'b' =>2 , 'c'=>3,); %hash=@array; print Dumper \%hash;

      Your version has the advantage that if some of the keys should change, you still would reset them to 0. If you want to reset all values to 0 you don't need the array anymore:

      @hash{keys %hash}=(0) x scalar(keys %hash);

      CORRECTION:Forgot () around the 0. And as cdarke pointed out to me the scalar is not needed as it is already in scalar context. But I tend to play safe with these things instead of trusting my memory

        Yes, but unneccessarily complicated

        Using the joy of x, your code can be shortened to:
        use strict; use warnings; use Data::Dumper; my %hash=('a'=>1 , 'b' =>2 , 'c'=>3,); my @keys = keys %hash; @hash{@keys} = (0) x @keys; print Dumper \%hash;

        Update:Note the parentheses around the zero. Without them you just get a string of zeros and the other values are undef. Also, you don't need scalar because the RHS of x is already in scalar context.
        Did you check that one.
        @hash{keys %hash}=0 x scalar(keys %hash);
        I gave me the following output as ,
        $VAR1 = { 'c' => '000', 'a' => undef, 'b' => undef };
        I want all the values of hash to '0'.