in reply to Recursive function always returns 0
imp's answer is correct. The whole point of recursion is, of course, that you have to propogate the answer back up the stack. In your case, you were discarding the return value from unpack_row, so the calling subroutine (also unpack_row) didn't get anything to work with.
Here's a more-or-less working version of your code. Note the return statement in the if(ref($hash) eq 'HASH') block. You may have to modify what you're returning; as I'm not exactly sure what you're trying to do.
use strict; use warnings; use Data::Dumper; # Prototype defined to avoid 'function not defined' warnings # on compilation. sub unpack_row{ my $hash = shift; my @row = @_; if(ref($hash) eq 'HASH'){ my $header = $hash->{'header'}; my @results = ( ); while(my ($key, $value) = each(%$hash)){ # Save the results the way you need them... push @results, unpack_row($value, (@row, $key)); } return (@results); # ... or whatever you return } else { print Dumper((@row, $hash)); return (@row, $hash); } } my $hash = {}; $hash->{'foo'}->{'bar'}->{'bat'} = 5; print unpack_row($hash, ());
I'll point out that you don't need prototypes; just leave off the parentheses "( ... )" when you define the subroutine unpack_row and you'll be all set.
Also, you don't need to shift @_; @_ is the thing shifted by default.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Recursive function always returns 0
by jpfarmer (Pilgrim) on Feb 14, 2007 at 20:40 UTC | |
by liverpole (Monsignor) on Feb 14, 2007 at 21:27 UTC | |
|
Re^2: Recursive function always returns 0
by jpfarmer (Pilgrim) on Feb 14, 2007 at 18:51 UTC |