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

In reply to Re: Variable scoping when a sub calls itself?? by GrandFather
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.