Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Updating A Hash Recursively

by ChemBoy (Priest)
on Sep 05, 2005 at 06:21 UTC ( [id://489152]=note: print w/replies, xml ) Need Help??


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

Replies are listed 'Best First'.
Re^2: Updating A Hash Recursively
by Anonymous Monk on Sep 06, 2005 at 01:55 UTC
    This is my code using recursive call.
    #!/usr/bin/perl use strict; use warnings; use Carp; my @lines = ('A', 'B', 'C'); my @tojoin = qw/X Y W/; my @new; sub closure; sub closure { my ($ary, $ret) = @_; if (length($ary->[0]) == 3) { return; } my @tmp; foreach (@$ary) { foreach my $to (@tojoin) { push @tmp, $_ . $to; } } push @$ret, @tmp; closure \@tmp, $ret; } closure \@lines, \@new; $, = ","; print @new;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://489152]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (1)
As of 2024-04-24 13:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found