Hi Meir,

You're assigning a new list (of key/value pairs) to the entire hash, so you overwrite all the existing keys.
To override any set keys and add additional keys, try this:

%hash = (%hash, key => value, key => value, key => value ... );

This is a common pattern for overriding default arguments, for example.

On 04/04/2011 04:26 PM, Meir Guttman 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


--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

_______________________________________________
Perl mailing list
[email protected]
http://mail.perl.org.il/mailman/listinfo/perl

Reply via email to