MarcoS
MarcoS

Reputation: 17711

Perl, how to lowercase all hash values?

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

Answers (5)

ikegami
ikegami

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

TLP
TLP

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

hobbs
hobbs

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

Kevin Brock
Kevin Brock

Reputation: 8944

This is a one liner using map:

my %newHash = map { $_ => lc $existingHash{$_} } keys %existingHash;

Upvotes: 6

friedo
friedo

Reputation: 66978

my %new = map { $_ => lc $old{$_} } keys %old;

Upvotes: 13

Related Questions