[Wellington-pm] Hash slices with missing keys

Ewen McNeill ewen at naos.co.nz
Wed Jul 19 19:19:47 PDT 2006


Hi,

If I have a hash with some fields in it, and I use slices to pick out
and swap over some of the values in the hash, and some of the keys
referenced in the slice do not exist, am I guarenteed to get undef for
the keys that don't exist?  Also is this warning/error free with "use
strict".  Experimentation says yes, but I'm wary that I'm relying on
some undocumented implementation quirk.

Eg,

@KEYS_A = qw(A B C D);
@KEYS_B = qw(E F G H);

%hash = (
  'A' => 'aaaaaa',
  'B' => 'bbbbbb',
  'C' => 'cccccc',
  'D' => 'dddddd',
  'G' => 'gggggg',
  'H' => 'hhhhhh'
);

@hash{@KEYS_A, @KEYS_B} = @hash{@KEYS_B, @KEYS_A};    # swap values over

Note how E and F are not present in %hash in the beginning.  What I want
to happen is that after the above code A and B are undef, and the
other values swap over as indicated.  And that appears to be the case,
but I'm not clear if this is documented behaviour.  Eg, perldata(1)
doesn't seem to say anything either way.

Failing this I'll need to copy over fields individually with some third
variable to hold the values in transit.

Ewen


More information about the Wellington-pm mailing list