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.
|
|---|
| 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 | |
by GrandFather (Saint) on Apr 15, 2008 at 22:47 UTC | |
|
Re^2: Variable scoping when a sub calls itself??
by cosmicperl (Chaplain) on Apr 15, 2008 at 22:54 UTC |