Let's say I have a hashref constant like the following:
use constant DOGS => {
Lassie => 'collie',
Benji => 'mutt',
Scooby => 'great dane',
Goofy => '???'
};
How can I dereference it properly to get say.. they keys out of it?
warn ref DOGS; # HASH at untitled line 12.
warn keys( %{DOGS} ); # Warning: something's wrong (empty list)
warn keys( DOGS ); # Type of arg 1 to keys must be hash (not constant item)
The following is the only way I can seem to make it work:
my $dogs = DOGS;
warn keys( %$dogs ); # LassieBenjiGoofyScooby at untitled line 15.
What am I doing wrong?
Dereferencing is the way of accessing the value in the memory pointed by the reference. In order to dereference, we use the prefix $, @, % or & depending on the type of the variable(a reference can point to a array, scalar, or hash etc).
Dereference a HASH First we print it out directly so you can see it is really a reference to a HASH. Then we print out the content using the standard Data::Dumper module. Then we de-reference it by putting a % sign in-front of it %$hr and copy the content to another variable called %h.
Dereferencing an array If you have a reference to an array and if you would like to access the content of the array you need to dereference the array reference. It is done by placing the @ symbol (the sigil representing arrays) in-front of the reference.
Hash References To get a hash reference, use the {key=>value} syntax instead, or prefix your variable name with a backslash like: %hash. Dereference a hash with %$hashref, with the $arrayref->{key} arrow for value references, or the %{array_ref_expression} syntax.
This will usually work for you:
%{DOG()}
Constants are generally just subs. But for ease (and looks), you might prefer to use Readonly
, as suggested in PBP.
Readonly::Hash my %DOG =>
( Lassie => 'collie'
, Benji => 'mutt'
, Scooby => 'great dane'
, Goofy => '???'
);
Perldoc is your friend: perldoc constants
You can get into trouble if you use constants in a context which automatically quotes barewords (as is true for any subroutine call). For example, you can't say $hash{CONSTANT} because "CONSTANT" will be interpreted as a string. Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bare- word quoting mechanism from kicking in. Similarly, since the "=>" operator quotes a bareword immediately to its left, you have to say "CONSTANT() => 'value'" (or simply use a comma in place of the big arrow) instead of "CONSTANT => 'value'".
warn keys %{DOG()}
should do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With