This is expected behavior, and is how aggregates have always worked in Perl.
(The same will happen with $array[$subscript] and @array = (list).)

If you want to update a hash non-destructively, use a hash slice:

  @hash{'key1', 'key2', 'key3'} = (value1, value2, value3);

Syntactically this form is fairly common:

  @hash{qw/key1 key2 key3/} = (...);

To complete the analogy with arrays, @array[1, 2, 7] = ("foo", "bar", "baz")
also performs an update only.

On Mon, Apr 4, 2011 at 4:26 PM, Meir Guttman <[email protected]> wrote:

>  Hi all!
>
>
>
> In one program of mine, I collect key/value pair scattered along the code
> using the
>
>  * $hash{key} = value;* form.
>
> But sometimes I have a bunch of keys/values that I tried to *add* to the
> hash in a single statement in the form of
>
>   *%hash = (key => value, key => value, key => value, ... );*
>
> see (executable) script below.
>
> To my surprise, the second form reinitialized the hash and practically
> erased whatever was there before. What I was left with is the result of the
> last statement.
>
> I cannot find any treatment of this issue in Perl's documentation (
> http://perldoc.perl.org/5.10.1/index.html).
>
> This IMHO is inconsistent.
>
> Any comments?
>
>
>
>   Meir
>
>
>
>
>
>
>
> *#!/usr/bin/perl*
>
> *use strict;*
>
> *my %hash;*
>
> * *
>
> *$hash{'01'} = 1;*
>
> *$hash{'02'} = 2;*
>
> *$hash{'03'} = 3;*
>
> *$hash{'04'} = 4;*
>
> * *
>
> *print "Before:\n", ("-" x 6), "\n";*
>
> *foreach my $key (sort keys %hash) {print "$key - $hash{$key}\n";}*
>
> * *
>
> *%hash = (*
>
> *  '05' => 5,*
>
> *  '06' => 6,*
>
> *  '07' => 7,*
>
> *  '08' => 8,*
>
> *  );*
>
> * *
>
> *print "After:\n", ("-" x 6), "\n";*
>
> *foreach my $key (sort keys %hash) {print "$key - $hash{$key}\n";}*
>
> _______________________________________________
> Perl mailing list
> [email protected]
> http://mail.perl.org.il/mailman/listinfo/perl
>



-- 
Gaal Yahas <[email protected]>
http://gaal.livejournal.com/
_______________________________________________
Perl mailing list
[email protected]
http://mail.perl.org.il/mailman/listinfo/perl

Reply via email to