Reputation: 1693
I have some code like so:
print "key $_ - $hJobT{$_}\n" foreach keys %hJobT;
%hJobT = map { $_ => 1 } %hJobT;
print "key $_ - $hJobT{$_}\n" foreach keys %hJobT;
When I run the program and print the results I get:
key office - 1
key recon - 1
key office - 1
key 1 - 1
key recon - 1
The first two results are from the first print statement and are expected.
The key 1 - 1
part is not expected.
To clarify - the code is in a loop which as it iterates, the key-values increment in certain conditions. For testing purposes I put an exit statement at the end of the loop so it only shows the first iteration results, hence whey they are '1'. (Just so it doesn't seem like I'm mapping 1s to 1s pointlessly.) Any ideas as to why I get the 1-1 mapping?
Upvotes: 2
Views: 103
Reputation: 57640
A hash is an even-valued list. Therefore, when using it in list context, you get all these keys and values:
@list = qw(a b);
%hash = @list; # valid!
@list = %hash; # valid, but bad style. And the ordering may change
So when you used the hash as an arg to map
, you created following list:
(
office => 1,
1 => 1,
recon => 1,
1 => 1
)
because map
saw
("office", 1, "recon", 1)
as it's list argument.
Upvotes: 11