The only problem is that this implementation
requires the keys to be reverse sorted (longest
to shortest-- remove the "reverse" on the sort
and it breaks).  To handle unordered names, try
this (note: I eliminated the replication of
parent hash node keys, as a personal preference):

use strict;
use Data::Dumper; $Data::Dumper::Indent=1;

my %hash = (
  "Foo" => 1,
  "Foo::Bar::Poo" => 1,
  "Foo::Bar" => 1,
  "Foo::Beer" => 1,
  "Foo::Beer::Nuts" => 1,
  "Foo::Beer::Nuts::Hmmm" => 1,
  "Foo::Bar::AgainHmmm" => 1,
);
print Data::Dumper->Dump([\%hash], [qw(%hash)]);

my %newhash;
foreach (keys %hash) {

    my @l = split /::/, $_;

    my $path = '';
    my $newhashref = \%newhash;

    for (my $ii = 0; $ii < @l; $ii++) {

        if (not exists ${$newhashref}{$l[$ii]}) {
            if ($ii < (@l - 1)) {
                ${$newhashref}{$l[$ii]} = {};
            } else {
                ${$newhashref}{$l[$ii]} = 1;
            }
        } else {
            if (($ii < (@l - 1)) &&
(${$newhashref}{$l[$ii]} == 1)) {
                ${$newhashref}{$l[$ii]} = {};
            }
        }
        $newhashref = (${$newhashref}{$l[$ii]});
    }
}
print Data::Dumper->Dump([\%newhash], [qw(%newhash)]);

__END__



--- $Bill Luebkert <[EMAIL PROTECTED]> wrote:
> Martin Moss wrote:
> <original text elided>
> 
> It would be hard to build on the fly since you don't
> know the depth yet.  You
> need to either re-structure the final hash or sort
> when complete.
> 
> use strict;
> use Data::Dumper; $Data::Dumper::Indent=1;
> 
> my %hash = (
>   Foo => 1,
>   Foo::Bar => 1,
>   Foo::Bar::Poo => 1,
>   Foo::Beer => 1,
>   Foo::Beer::Nuts => 1,
>   Foo::Beer::Nuts::Hmmm => 1,
>   Foo::Bar::AgainHmmm => 1,
> );
> print Data::Dumper->Dump([\%hash], [qw(%hash)]);
> 
> my %newhash;
> foreach (reverse sort keys %hash) {
> 
>       my @l = split /::/, $_;
> 
>       my $path = '';
>       for (my $ii = 0; $ii < @l; $ii++) {
> 
>               $path .= "'}{'" if $path;
>               $path .= join '::', @l[0..$ii];
> 
>               my $exists = eval "exists \$newhash{'$path'}" ||
> 0;
>               if (not $exists) {
>                       if ($ii < scalar @l - 1) {
>                               eval "\$newhash{'$path'} = {}";
>                       } else {
>                               eval "\$newhash{'$path'} = 1";
>                       }
>               }
> 
>       }
> }
> print Data::Dumper->Dump([\%newhash],
> [qw(%newhash)]);
> 
> __END__


__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com
_______________________________________________
Perl-Unix-Users mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to