Perl: print a string from a hash containing a reference to it
Sorry if this is a bad title.
I have the following hash:
my %map = (
'key1', 'hello',
'key2', \'there'
);
print Dumper(\%map);
output:
$VAR1 = {
'key2' => \'there',
'key1' => 'hello'
};
I want to print the value to 'key2'
. Here's what I've tried:
print "$map{key2}" => SCALAR(0x2398b08)
print "$$map{key2}" =>
print "$map->{key2}" =>
my goal:
print [some magic thing] => there
I'm new to perl, so I'm not 100% unaware of how links behave and how to play them out. How do I get what I'm looking for?
source to share
$map{key2}
is a reference to a scalar value \'there'
, so you need to dereference it
Yours $$map{key2}
and is $map->{key2}
treated $map
as a hash reference, but it doesn't even exist, so that's not correct
You should use curly braces to eliminate the evaluation order
${ $map{key2} }
- Is this what you want. Or you can write it down in two steps
my $val = $map{key2};
print $$val, "\n";
source to share
$map{key2}
returns the value of the required element. The element is a link to a string. [1] If you want to print the string this link refers to, you need to dereference it.
say ${ $map{key2} };
Literature:
- I doubt this is intentional! This would definitely indicate a bug somewhere.
source to share
I like to add the following line to all my perl scripts: use strict;
This will save you the trouble of scoping your variables. This requires you to encompass all your variables, at least "mine".
Then you can directly print the value (of the hash associated with "key2"),
without an intermediate step, by first copying it to another variable.
print ${$map{'key2'}}, "\n";
source to share