in reply to Hash Push

I'm not sure why people fealt this question wasn't sufficiently clear, so I will expand on it. I've already written the code, I'm just trying to make it cleaner and easier to maintain by the next guy. The part that I don't like is the refrences, and I was wondering if any of the Perl Monk Gurus could enlighten me with better ways of doing this without changing the over-all structure. By that I mean the routine must be recursive, the keys are associated with arrays, not scalars, and these arrays are grown as new values are found for given keys.

Basically I'm recursivly filling a particular data structure, and I'm looking for the cleanest way to do it.

Replies are listed 'Best First'.
RE: RE: Hash Push
by merlyn (Sage) on Aug 16, 2000 at 22:11 UTC
    You're not recursively filling a recursive data structure though, so the routine should not be passing data to merge: it should either be accessing a single reference and updating in place, or accessing a global (gack!).

    For example:

    my %global_data; fill_recursively(\%global_data, 10); sub fill_recursively { my $data_href = shift; # hashref to modify my $count = shift; # what level are we push @{$data_href->{"key $_"}}, "level $count" for 1..$count; fill_recursively($data_href, $count - 1) if $count > 1; } use Data::Dumper; print Dumper(\%global_data);
    The push is accessing the global data directly. Put whatever you want in there. Does that help?

    -- Randal L. Schwartz, Perl hacker

      Hey, I like that... Could I hide the whole thing too?
      Maybe write:
      sub GetData { my %data; sub Recursive { # do stuff # push onto %data # call Recursive if appropriate } Recursive(); return \%data; } my %data = %{GetData()}; # Can this be cleaner?
        Well, I'm not sure why you'd want to do that. For one, you now have nested subroutines with the ol' "Value won't stay shared" in the middle to boot. If you control the call to your subroutine, you can require they pass it by reference as the first parameter. If you don't, wrapper it up in a helper routine:
        sub routine_that_they_call { my @args = @_; my %data_to_be_filled; recursive_subroutine(\%data_to_be_filled, @args); return \%data_to_be_filled; }
        Now you don't have to define a nested subroutine.

        -- Randal L. Schwartz, Perl hacker