-1

I have a Perl hash (from some legacy code) but am unable print out the the keys.

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

e.g. here's the output I get:

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

I've read this Type of argument to keys on reference must be unblessed hashref or arrayref but not sure how to apply it in this case.

Is there a way of fixing this?

====

UPDATE

I've also tried:

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

but still get Type of argument to keys on reference must be unblessed hashref or arrayref

UPDATE 2

I can see I have the key a_key but I'm unable to print out its values. E.g. debugging with Carp::REPL I get:

$ 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

UPDATE 3

Using Data::Dumper in the REPL I get:

$ 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.
Snowcrash
  • 80,579
  • 89
  • 266
  • 376
  • @ikegami can you elaborate? – Snowcrash Jul 25 '17 at 17:35
  • I just re-ran the code and got the same error message. – Snowcrash Jul 25 '17 at 17:37
  • 1
    The `.` sets scalar context, but when you fix this `print "keys: ", keys(%$href), "\n";` you'll get all keys concatenated into one word. You can do `print "$_ " for keys %$href; print "\n";`, or for one per line `say for keys %$href;` – zdim Jul 25 '17 at 18:12

1 Answers1

6

First of all, you have a precedence problem. You are doing

keys($val . "\n")

instead of

keys($val) . "\n"

Secondly, the syntax for keys[1] is

keys HASH

meaning you need

keys(%$val)

Finally, you are calling keys in scalar context, which returns the number of keys in the hash. Call it in list context to get the keys of the hash. For example,

say "Keys: ", join ", ", keys(%$val);

  1. There were a few versions where Perl experimented with allowing keys $ref, but the experiment was discontinued in 5.24. Avoid that!
ikegami
  • 367,544
  • 15
  • 269
  • 518