http://www.perlmonks.org?node_id=489152


in reply to Updating A Hash Recursively

Your code does update the original hash, it just doesn't do what you expected it to. In this case, it's because your expectation is at fault: when you call keys %line, you enumerate the keys of the hash at that point in time—that is to say, ("A","C","B") (note the disorder, since hashes don't preserve key order). You're wanting it to magically detect that you have added a key to the hash, and append that to the queue of keys to be processed, which is not in fact how Perl hashes work.

All is not lost, however—you can achieve the desired effect much more economically with a little creative iteration:

my @list = "A".."C"; my @tojoin = "W".."Z"; ITEM: for (my $i = 0; $i <= $#list; $i++) { for (map "$list[$i]$_", @tojoin) { push @list,$_; last ITEM if /^AYW$/; } } use Data::Dumper; print Dumper \@list;

As an added benefit, this code produces the entries in the order you were probably expecting them in, and prevents annoying errors that would inevitably arise as side-effects of that problem.

If, of course, you really do need the results in the hash form shown in the original post, you can achieve that by adding either of the following lines to the end of the code in place of the call to Dumper:

@hash{@list} = (1) x @list; $hash{$_} = 1 for @list;



If God had meant us to fly, he would *never* have given us the railroads.
    --Michael Flanders