in reply to Hash key manipulation question

Sometimes it's easier to do it all backwards:

use strict; use warnings; use Data::Dumper; my @a = ( 1, 2, 3, "a" ); my %Hash = do { my $hashref = 1; $hashref = { $_ => $hashref } for reverse @a; %{$hashref}; }; print Dumper \%Hash;

This algorithm is very similar to one used to create linked lists, demonstrated in Mastering Algorithms with Perl, published by O'Reilly & Associates.

The way this works is by assigning your final value to $hashref. Then you work backwards through @a, setting $hashref equal to $hashref->{a}=1, and then to $hashref->{3}{a}=1, and then to $hashref->{2}{3}{a}=1, and so on, each time adding one more higher layer. In the end, you asked for %Hash, not $hashref, so this snippet dereferences $hashref for you and hands you %Hash. The do{...} block is used to limit the scope of $hashref, and to compartmentalize the entire operation in one nice little package.

Enjoy!


Dave