A function which will return an array containing all name/value pairs from a multilevel hash/array... for example if you have:

my %VAR; $VAR{SCALAR} = "test scalar"; $VAR{ARRAY}[0] = "test array"; $VAR{HASH}{NAME}[0] = "test hash array 1"; $VAR{HASH}{NAME}[1] = "test hash array 2"; $VAR{HASH}{NAME}[2]{SOMEHASH} = "test hash array hash 1"; $VAR{HASH}{NAME}[2]{ANOTHERHASH} = "test hash array hash 2";
And pass the function as:

getRefValues( "\$VAR", \%VAR );


Then the return would be an array containing:

$VAR{HASH}{NAME}[0] = (test hash array 1) $VAR{HASH}{NAME}[1] = (test hash array 2) $VAR{HASH}{NAME}[2]{ANOTHERHASH} = (test hash array hash 2) $VAR{HASH}{NAME}[2]{SOMEHASH} = (test hash array hash 1) $VAR{ARRAY}[0] = (test array) $VAR{SCALAR} = (test scalar)
sub getRefValues{ my($name, $ref) = @_;
# A sub that recursively calls itself to drill down a tree of hashes/arrays until all scalar values are found
# The final return is a listing of all absolute name/value pairs

#Usage: 	getRefValues( "nameofrefvar", refvar);
#e.g.	getRefValues("\%VAR", \%VAR );
#	getRefValues("\@VAR", \@VAR );

  my @values;
  
  if ( my $type = ref( $ref  ) )
  {
    if ( $type eq "ARRAY" )
    {
      my $indx=0;
      
      #for each item in the array...
      my $item;
      foreach $item ( @$ref )
      {
        #Check each array item for sub-values, , add the return to the current array of values
	push (@values, getRefValues("$name\$indx\", $item) );
	$indx++;
      }
    }
    elsif ( $type eq "HASH" )
    {
      #For each key in the hash....
      my $key;
      foreach $key ( keys ( %$ref) )
      {
        #Call myself to search for values in current key, add the return to the current array of values
	push (@values, getRefValues( "$name\{$key\}", $$ref{$key} ) );
      }
    }
  }
  else
  {
    #Process ends when we get the final item (a scalar)
    push (@values, "$name = ($ref)") ;
  }
  return @values;
}

Replies are listed 'Best First'.
Re: Name/pair values from a multilevel hash/array
by diotalevi (Canon) on Nov 24, 2004 at 21:11 UTC
    Are you really making data like this? This is a symbolic references bug just itching to happen.