in reply to Variable scoping when a sub calls itself??

but $hashVar is global. Why should HashClean recreate it? If you want a new instance of $hashVar every time you enter HashClean then $hashVar needs to be local to HashClean.

It seems that what you are trying to do is recursively traverse a mixed hash and array structure and clean it up. Maybe the following will help:

use strict; use warnings; sub clean { my $ref = shift; if ('HASH' eq ref $ref) { clean ($ref->{$_}), $ref->{$_} = undef for keys %$ref; } elsif ('ARRAY' eq ref $ref) { clean ($_), $_ = undef for @$ref; } } my $hashvar = { emp => {}, hemp => {splay => {}, hay => {go => 1, ho => {},}, tay => [], may => [ +'way'],}, }; clean ($hashvar); $hashvar = undef;

Update: rereading the OP I see that deleting the whole structure is not quite what you want, but the code above should still be a good starting point for getting to where you want to go. In fact the following may just do the trick:

use strict; use warnings; use Data::Dump::Streamer; sub clean { my $ref = $_[0]; if ('HASH' eq ref $ref) { clean ($ref->{$_}) and delete $ref->{$_} for keys %$ref; return ! keys %$ref; } elsif ('ARRAY' eq ref $ref) { clean ($ref->[$_]) and delete $ref->[$_] for reverse 0 .. $#$r +ef; return ! @$ref; } else { return ! defined $ref; } } my $hashvar = { emp => {}, hemp => {splay => {}, hay => {go => 1, ho => {},}, tay => [], may => [ +'way'],}, }; clean ($hashvar); Dump ($hashvar);

prints:

$HASH1 = { hemp => { hay => { go => 1 }, may => [ 'way' ] } };

Tip for the future - show what you expect as well as what you get.


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: Variable scoping when a sub calls itself??
by moritz (Cardinal) on Apr 15, 2008 at 22:24 UTC
    Don't you think it cleans too much? ;-)

    cosmicperl wants to delete pairs from hashes where the values are empty hash or array refs. After your sub runs, $hashvar looks like this:

    $hashvar = { 'hemp' => undef, 'emp' => undef };

    No need for recursion to achieve that, perl's garbage collector does the rest when you just delete the hash values ;-)

      I noticed that that was not what OP was after on re-reading the node (cf my update). My initial assumption was that OP needed to forcibly delete each node in the structure to get around leaks due to circular references or some such.


      Perl is environmentally friendly - it saves trees
Re^2: Variable scoping when a sub calls itself??
by cosmicperl (Chaplain) on Apr 15, 2008 at 22:54 UTC
    Thanks for your update. Looks a lot neater than my code (which did work when I sorted out the variable names). And yes I did want all the info, just not the empty hashes and arrays. I'll make sure to post what output I want in the future.

    Lyle