And pass the function as: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";
getRefValues( "\$VAR", \%VAR );
$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;
}
In reply to Name/pair values from a multilevel hash/array by darkphorm
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |