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 ;-)


In reply to Re: Variable scoping when a sub calls itself?? by moritz
in thread Variable scoping when a sub calls itself?? by cosmicperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.