How do you directly dereference a hash reference stored in another hash?

Viewed 54

If I store a reference to a hash in another hash, is it possible to directly dereference it without using temporary variables?

$myhash{"color"}="blue";
$myhash{"weight"}=12;

# Store a reference to %myhash in $other_hash{"key1"}

$other_hash{"key1"}=\%myhash;

# Use that reference with the help of a temporary variable $temp_ref - it works

$temp_ref=$other_hash{"key1"};
print join(" ",keys %$temp_ref),"\n";

# Try using that reference without a temporary variable -
# this produces an error "Scalar found where operator expected". Why?

print join(" ",keys %($other_hash{"key1"})),"\n";

Is there a way to dereference the %hash in the example above without using the temporary variable $temp_ref?

1 Answers

You need curly brackets rather than parentheses:

print join(" ",keys %{ $other_hash{"key1"} }), "\n";
#                 ---^-- here            --^-- and here
Related