in reply to dereferencing hash & array refs

Recursive code with a little piece of testing data:
use strict; my @result; my @a = (1, 2, [3, [4, 5]], 6, [7, 8, [9,10], [11, 12]], {1=>13, 2=>{2 +=> 14}}); de_ref(\@result, \@a); print(join(",",@result));#expect 1,2,3,4,5,6,7,8,9,10,11,12,13,14 sub de_ref { my ($result, $source) = @_; if (!ref($source)) { push @{$result}, $source; } else { if (ref($source) eq "ARRAY") { foreach my $ele (@{$source}) { de_ref($result, $ele); } } elsif (ref $source eq "HASH") { foreach my $ele (values %{$source}) { de_ref($result, $ele); } } elsif (ref $source eq "SCALAR") { push @{$result}, $$source; } } }
Two reminders about this piece of code:
  1. ref of types other than scalar, array and hash are ignored (those being ignored include REF, CODE, and GLOB), as it looks like you only want those three types
  2. assume that there is no circular ref

Replies are listed 'Best First'.
Re: Re: dereferencing hash & array refs
by parv (Parson) on Feb 09, 2003 at 21:30 UTC

    I did not imply that somebody does the work for me. But now that pg had already done that (create the recursive version), i can only thank him.