[tpm] Populating an unfixed number of hash elements

Viktor Pavlenko vvp at cogeco.ca
Fri May 9 11:00:39 PDT 2008


>>>>> "SF" == Shaun Fryer <sfryer at sourcery.ca> writes:

    SF> Actually, this may be more what you intended. However, notice
    SF> that the key/value may get over-ridden in case of
    SF> collisions.

If she avoids global hash, there will be no problem ...

    SF> sub mk_href {
    SF>     my ($href, $keystr, $value) = @_;
    SF>     my @keys = split /::/, $keystr;
    SF>     my $last_key = pop @keys;
    SF>     my $_href = {};
    SF>     $_href->{$last_key} = $value;
    SF>     while (my $key = pop @keys) {
    SF>         my $elem = {};
    SF>         $elem->{$key} = $_href;
    SF>         $_href = $elem;
    SF>     }
    SF>     $href->{$_} = $_href->{$_} for keys %$_href;
    SF> }

... and then this:

-------------------------------------------------------------------->8
sub mk_href
{
    my ($keystr, $value) = @_;
    my @keys = reverse split /::/, $keystr;
    helper($value, @keys);
}

sub helper
{
    my ($val, @keys) = @_;
    my $k = pop @keys;
    my $hr = {};
    $hr->{$k} = ($#keys == -1) ? $val : helper($val, @keys);
    return $hr;
}
-------------------------------------------------------------------->8

-- 
Viktor



More information about the toronto-pm mailing list