[tpm] Populating an unfixed number of hash elements

Shaun Fryer sfryer at sourcery.ca
Fri May 9 10:08:19 PDT 2008


Actually, this may be more what you intended. However, notice that the key/value
may get over-ridden in case of collisions. For instance $string1 will produce

    { some => { string => { or => { elements => 'a value' } } } }

But the value of the key "string" will get overwritten by $string2 to form the
following.

    { some => { string => 12 } }

Not sure how you'd work around this except to suggest that your proposed values
are in fact keys with a value of 1. (ie. { some => { string => { 12 => 1 } } }).

################################################################################
use strict;
use warnings;
use Data::Dumper;

my $string1="some::string::of::elements";
my $string2="some::string";
my $string3="some::string::of::other::elements";
my $string4="another::set::of::keys";

my %hash = ();

mk_href(\%hash, $string1, "a value");
print Dumper \%hash;

mk_href(\%hash, $string2, 12);
print Dumper \%hash;

mk_href(\%hash, $string3, "a really long string that takes up pages");
print Dumper \%hash;

mk_href(\%hash, $string4, "something else again.");
print Dumper \%hash;

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

On Fri, May 09, 2008 at 12:58:49PM -0400, Shaun Fryer wrote:
> ################################################################################
> use strict;
> use warnings;
> use Data::Dumper;
> 
> my $string1="some::string::of::elements";
> my $string2="some::string";
> my $string3="some::string::of::other::elements";
> my $string4="another::set::of::keys";
> 
> my $href={};
> 
> $href = mk_href($string1, "a value");
> print Dumper $href;
> 
> $href = mk_href($string2, 12);
> print Dumper $href;
> 
> $href = mk_href($string3, "a really long string that takes up pages");
> print Dumper $href;
> 
> $href = mk_href($string4, "something else again.");
> print Dumper $href;
> 
> sub mk_href {
>     my ($keystr, $value) = @_;
>     my @keys = split /::/, $keystr;
>     my $last_key = pop @keys;
>     my $href = {};
>     $href->{$last_key} = $value;
>     while (my $key = pop @keys) {
>         my $elem = {};
>         $elem->{$key} = $href;
>         $href = $elem;
>     }
>     return $href;
> }
> ################################################################################


More information about the toronto-pm mailing list