[Wellington-pm] Hash slices with missing keys
Grant McLean
grant at mclean.net.nz
Wed Jul 19 19:32:07 PDT 2006
On Thu, 2006-07-20 at 14:19 +1200, Ewen McNeill wrote:
> 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
Yes, for every element in the union of @KEYS_A and @KEYS_B, the
corresponding key in %hash will exist after the assignment, regardless
of whether it existed before and regardless of whether it ends up with a
value of undef.
> Failing this I'll need to copy over fields individually with some third
> variable to hold the values in transit.
Nope, you're safe to rely on Perl doing the intermediate storage thing
for you.
Cheers
Grant
More information about the Wellington-pm
mailing list