首页 > 解决方案 > 如何直接取消引用存储在另一个哈希中的哈希引用?

问题描述

如果我将一个哈希的引用存储在另一个哈希中,是否可以在不使用临时变量的情况下直接取消引用它?

$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";

有没有办法在不使用临时变量 $temp_ref 的情况下取消引用上面示例中的 %hash?

标签: perlhashreferencekey

解决方案


您需要大括号而不是括号:

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

推荐阅读