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

It might be very confusing that $hashvar is passed as a parameter to your sub, and at the same time it is used under its original name, thus referencing a part (or subset) of the data structure with a differenct name.

Don't do that. Don't mix $hashvar with $hashref.

Also don't call subs with a leading '&', it might have unexpected behaviour.

Update: Here is a small script that does what you want, by constructing a new copy of the data structure instead of deleting items:

use strict; use warnings; use Data::Dumper; use Scalar::Util qw(reftype); my $hashvar = { emp => {}, hemp => { splay => {}, hay => { go => 1, ho => {}, }, tay => [], may => [ 'way' ], }, }; sub clean { my $ref = shift; return $ref unless ref $ref; if (reftype($ref) eq 'HASH'){ my %result; for (keys %$ref){ my $tmp = clean($ref->{$_}); $result{$_} = $tmp if (defined $tmp); } if (keys %result){ return \%result; } else { return; } } elsif (reftype($ref) eq 'ARRAY'){ return @$ref ? $ref : undef; } } print Dumper($hashvar, clean($hashvar)); __END__ $VAR1 = { 'hemp' => { 'may' => [ 'way' ], 'tay' => [], 'hay' => { 'ho' => {}, 'go' => 1 }, 'splay' => {} }, 'emp' => {} }; $VAR2 = { 'hemp' => { 'may' => $VAR1->{'hemp'}{'may'}, 'hay' => { 'go' => 1 } } };

I'm too tired to tell if it really works, so check it yourself ;-)

Replies are listed 'Best First'.
Re^2: Variable scoping when a sub calls itself??
by cosmicperl (Chaplain) on Apr 15, 2008 at 22:50 UTC
    Thanks for the tips. Fixed it now. And don't worry, I always use () with & so as not to get strange behavior. Just like being able to quickly distinguish between my routines and perl's.

      And don't worry, I always use () with & so as not to get strange behavior.

      & also disables prototypes.

      use strict; use warnings; sub my_splice(\@$;$@) { my ($array, $start, $length, @insert) = @_; return splice(@$array, $start, $length, @insert); } { my @array = qw( a b c ); splice(@array, 1, 1, qw( d e )); print(@array, "\n"); # adec } { my @array = qw( a b c ); my_splice(@array, 1, 1, qw( d e )); print(@array, "\n"); # adec } { my @array = qw( a b c ); &my_splice(@array, 1, 1, qw( d e )); print(@array, "\n"); # Can't use string ("a") as an ARRAY ref whil +e "strict refs" in use at !.pl line 6. }

      Now, you could argue that prototypes should be avoided, but they are used by many modules.