lost-theory

The blog of Steven Kryskalla.


 

Perl - how to get the keys of a constant hashref

written by stevek, on Jul 12, 2010 10:59 PM.

How do you get the keys of a constant hashref?

$> use constant A => { 1 => 100, 2 => 200, 3 => 300}
()
$> A
{ 1 => 100, 2 => 200, 3 => 300 }

$> keys A
ERROR: Type of arg 1 to keys must be hash (not constant item) at (eval
13) line 3, at EOF
$> keys %A
()
$> (keys %{A})
Ambiguous use of %{A} resolved to %A at (eval 18) line 1, <IN> line 8.
()

All seems lost until you learn that a constant is actually a function. You can leave off the parentheses to call a function in perl, but in this case you have to call the function to make it clear.

$> (keys A())
ERROR: Type of arg 1 to keys must be hash (not constant item) at (eval
16) line 3, near "A())
$> (keys %{A()})
(1, 3, 2)

Leave a Reply