How can I dereference the hashref constant?

Say I have a hashref constant, as shown below:

use constant DOGS => { Lassie => 'collie', Benji => 'mutt', Scooby => 'great dane', Goofy => '???' }; 

How can I dereference it correctly to say ... are they the keys to it?

 warn ref DOGS; # HASH at untitled line 12. warn keys( %{DOGS} ); # Warning: something wrong (empty list) warn keys( DOGS ); # Type of arg 1 to keys must be hash (not constant item) 

The following is the only way to make it work:

 my $dogs = DOGS; warn keys( %$dogs ); # LassieBenjiGoofyScooby at untitled line 15. 

What am I doing wrong?

+4
source share
3 answers

This usually works for you:

 %{DOG()} 

Constants are usually just submarines. But for convenience (and views) you can use Readonly , as suggested by PBP.

 Readonly::Hash my %DOG => ( Lassie => 'collie' , Benji => 'mutt' , Scooby => 'great dane' , Goofy => '???' ); 
+12
source

Perldoc is your friend: perldoc constants

You may have problems if you use constants in a context that automatically quotes words (like true for any subroutine call). For example, you cannot say $ hash {CONSTANT} because "CONSTANT" is interpreted as a string. Use $ hash {CONSTANT ()} or $ hash {+ CONSTANT} to prevent the mechanism of quoting words from being kicked. Similarly, since the "=>" operator instantly quotes to your left, you should say: "CONSTANT () => 'value'" (or just use a comma instead of the big arrow) instead of "CONSTANT =>" value ".

warn keys %{DOG()} should do the trick.

+5
source

Put it in a list context ...

 warn keys(%{(DOGS)}); 
-1
source

Source: https://habr.com/ru/post/1307185/


All Articles