[Israel.pm] Case Study: Splitting a Hash into Two

Mikhael Goikhman migo at homemail.com
Wed Jul 14 12:43:05 PDT 2004


On 14 Jul 2004 21:48:30 +0300, Shlomi Fish wrote:
> 
> Today I hanged around FreeNode's #perl channel. Someon asked for a way to 
> generate two hashes out of one, with one containing only the keys that start 
> with underscore, and the other the rest. After some thinking and planning I 
> came out with this code:
> 
> <<<
> sub split_hash
> {
>     my $h = shift;
>     # us is underscore not the United States.
>     my (%us_hash, %non_us_hash);
>     while (my ($k, $v) = each(%$h))
>     {
>         (($k =~ /^_/o) ? \%us_hash : \%non_us_hash)->{$k} = $v;
>     }
>     return (\%us_hash, \%non_us_hash);
> }
> >>>
> 
> (tested, BTW).

I think I would do it this way (at least if the run time is cheap):

	my %under_hash = map { $_ => $hash{$_} } grep  /^_/, keys %hash;
	my %other_hash = map { $_ => $hash{$_} } grep !/^_/, keys %hash;

Regards,
Mikhael.

-- 
perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'



More information about the Perl mailing list