Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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


In reply to Re: Updating A Hash Recursively by ChemBoy
in thread Updating A Hash Recursively by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-03-28 10:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found