in reply to trees of word lists

I'm not sure what you might consider obscure so the following non-recursive code might be either obscure or elegant:

use strict; use warnings; use Data::Dump::Streamer; my @list1 = qw/Truck Car Byke/; my @list2 = qw/Truck Car Scooter/; my @list3 = qw/Truck Trailer Skates/; my %tree; for my $list (\@list1, \@list2, \@list3, ) { my $node = \%tree; $node = $node->{shift @$list} ||= {} while @$list; } Dump \%tree;

Prints:

$HASH1 = { Truck => { Car => { Byke => {}, Scooter => {} }, Trailer => { Skates => {} } } };

Perl's payment curve coincides with its learning curve.

Replies are listed 'Best First'.
Re^2: trees of word lists
by lostjimmy (Chaplain) on Jan 22, 2009 at 20:18 UTC

    Every day I realize I have more to learn. Your code is much more elegant than my recursive solution.

    use warnings; use strict; use Data::Dumper; my @lists = ([qw/Truck Car Bike/], [qw/Truck Car Scooter/], [qw/Truck Trailer Skates/]); my %tree; for my $list (@lists) { to_tree(\%tree, $list); } print Dumper(\%tree); sub to_tree { my ($head, $list) = @_; my $node = shift @$list; return unless defined $node; $head->{$node} ||= {}; to_tree($head->{$node}, $list); }

      I am not even sure I would call your code inelegant. I find it very easy to understand, and very much what I would have written.

      --MidLifeXis