in reply to Re: re-initialize the hash
in thread re-initialize the hash

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;

Replies are listed 'Best First'.
Re^3: re-initialize the hash
by jethro (Monsignor) on Apr 01, 2010 at 08:56 UTC
    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'.