Reputation: 17711
I need to copy a (one-level) hash to a new one, with all values lowercased.
Do you know a smart method (just to avoid an ugly foreach... ;-)
Upvotes: 5
Views: 2131
Reputation: 385915
Just another way (that's not as cool now that I know you want a copy of the hash).
my %new = %old;
$_ = lc for values %new;
Upvotes: 3
Reputation: 67890
In the spirit of fun, here's a solution using the somewhat obscure each
function. (Don't believe I have ever used it before.)
$new{$key} = lc $val while ($key,$val) = each %old;
Upvotes: 2
Reputation: 240020
Just for fun, a different angle to look at the same thing:
my %new_hash;
@new_hash{keys %old_hash} = map lc, values %old_hash;
And yes, the keys
and values
functions are guaranteed to produce their lists in corresponding order, provided you don't modify the hash they're working on between calling one and the other.
Upvotes: 6
Reputation: 8944
This is a one liner using map
:
my %newHash = map { $_ => lc $existingHash{$_} } keys %existingHash;
Upvotes: 6