Don't ask to ask, just ask | |
PerlMonks |
Re: Scoping problems with recursive functionby fullermd (Priest) |
on Mar 19, 2010 at 18:49 UTC ( [id://829680]=note: print w/replies, xml ) | Need Help?? |
Now, on a broader note. Your %dependencies hash is a list, by key, of the keys that key depends on. This is inconvenient for what you're trying to do, which is why you're jumping through some hoops. To put the function in english:
Now, note that in the middle, if you decide to delete this key, you're still continuing to loop over its dependencies. So you'd really want to break out of there. But better, you can avoid that loop completely, and just ask the question "am I ($key) one of the elements in this array?" with grep:
That saves you writing the loop. But, let's step back. The key you're deleting probably isn't a dependency for most of the keys in the hash. If you're going to be calling this a lot, it can be a little annoying spending all that time searching over lists you're not in. You're having to do that because your list shows the dependencies of each key. But it would be even more convenient if instead it showed the keys that depend on each key. Then you could just loop over that list, deleting stuff. And it's pretty each to build that list from the one you have. Something like:
Now you've got a lookup you can just loop directly over, and you can get even shorter. Obviously it costs some time and memory to build that %requiredby list, but if you're going to call the delete often, it's worth it. New version (tested):
Of course, won't catch infinite loops, like if we set four to depend on three as well. That's left as an exercise for the reader :)
In Section
Seekers of Perl Wisdom
|
|