Perl:引用键的参数类型必须是非散列的hashref或arrayref

时间:2017-07-25 17:30:15

标签: perl hash reference

我有一个Perl哈希(来自一些遗留代码),但我无法打印出密钥。

  if (ref $val eq ref {}) {
    print "Keys: " . keys $val . "\n";

e.g。这是我得到的输出:

VAL: HASH(0x7ff0898eda70)
Type of argument to keys on reference must be unblessed hashref or arrayref

我已阅读此Type of argument to keys on reference must be unblessed hashref or arrayref但不确定如何在这种情况下应用它。

有没有办法解决这个问题?

====

更新

我也试过了:

    print "Keys: " . keys %$val . "\n";

但仍然获得Type of argument to keys on reference must be unblessed hashref or arrayref

更新2

我可以看到我有密钥a_key,但我无法打印出它的值。例如。调试Carp::REPL我得到:

$ print $val;
1$ HASH(0x7fb1e0828f00)    
$ print %$val;
1$ a_keyARRAY(0x7fb1e0828e28)
$ print %$val{'a_key'}
Compile error: syntax error at (eval 412) line 63, near "$val{"
BEGIN not safe after errors--compilation aborted at (eval 412) line 63, <FIN> line 6.
$ print $val{'a_key'}
Use of uninitialized value in print at (eval 413) line 63, <FIN> line 7.
1

更新3

在REPL中使用Data::Dumper我得到:

$ print Dumper( $val );
$VAR1 = {
          'a_key' => [
                     'long_value'
                   ]
        };
1$ print Dumper( %$val );
$VAR1 = 'a_key';
$VAR2 = [
          'long_value'
        ];
1$ print %$val[1]
Compile error: syntax error at (eval 450) line 63, near "$val["
BEGIN not safe after errors--compilation aborted at (eval 450) line 63, <FIN> line 44.
$ print %$val{'a_key'}
Compile error: syntax error at (eval 451) line 63, near "$val{"
BEGIN not safe after errors--compilation aborted at (eval 451) line 63, <FIN> line 45.
$ print $val[1]     
Use of uninitialized value in print at (eval 452) line 63, <FIN> line 46.

1 个答案:

答案 0 :(得分:6)

首先,您有一个优先问题。你在做什么

keys($val . "\n")

而不是

keys($val) . "\n"

其次,keys [1] 的语法是

keys HASH

意味着你需要

keys(%$val)

最后,您在标量上下文中调用keys,它返回散列中的键数。在列表上下文中调用它以获取哈希的键。例如,

say "Keys: ", join ", ", keys(%$val);
  1. 有几个版本的Perl试验允许keys $ref,但实验在5.24中已停止。避免这样!