morrin has asked for the wisdom of the Perl Monks concerning the following question:
Hi,
I basically have a function that I would like to call recursively to delete certain values from a hash. These values are interdependent, so if I need to delete a certain value, I also want to delete all other values that depend on that one.
For example, I have something like
my %hash = ( 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' + => 5); my %dependencies =( 'one' => [], 'two' => [], 'three' => ['four'], 'fo +ur' => ['one','two'], 'five' => ['three']);
so if I need to delete 'one' from the list, I must also then also delete the keys 'three' and 'four' from the hash.
So my function looks something like
sub my_del($){ while (my $key = each (%hash)){ print "KEY = $key\n"; foreach (@{ $dependencies{$key} }){ if( $_ eq $_[0]){ print"Going to call sub for $key\n"; my_del($key); } } print"\n"; } delete $hash{$_[0]}; print "Deleting $_[0]\n"; } my_del('one');
The resulting output is
KEY = three KEY = five KEY = one KEY = two KEY = four Going to call sub for four Deleting four KEY = three KEY = five KEY = one KEY = two Deleting one
It is as if the "each" somehow is like a "global" in that when I call the function recursively, it remembers at which value it was at and continues from there.
Note that sometimes it will work depending of the ordering if the hash. eg, it works fine when I used
my %dependencies =( 'one' => [], 'two' => [], 'three' => ['one'], 'fou +r' => ['three','two'], 'five' => ['three']);
I got
KEY = three Going to call sub for three KEY = five Going to call sub for five KEY = one KEY = two KEY = four Deleting five KEY = three KEY = one KEY = two KEY = four Going to call sub for four Deleting four KEY = three KEY = one KEY = two Deleting three KEY = one KEY = two Deleting one
Any help would be gratefully appreciated. I am from a "C" background and I had thought it would work like I'd have expected to in "C". i.e. when each recursive call is made, local variables are created and everything starts again for that function. Thanks
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Scoping problems with recursive function
by fullermd (Vicar) on Mar 19, 2010 at 18:14 UTC | |
|
Re: Scoping problems with recursive function
by kennethk (Abbot) on Mar 19, 2010 at 18:15 UTC | |
by AnomalousMonk (Archbishop) on Mar 19, 2010 at 18:54 UTC | |
|
Re: Scoping problems with recursive function
by fullermd (Vicar) on Mar 19, 2010 at 18:49 UTC | |
by Xiong (Hermit) on Mar 20, 2010 at 16:41 UTC |