Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl: print a string from a hash that contains a reference to it

Tags:

perl

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 out the value at '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% clear yet on how references behave and how to dereference them. How do I get what I'm looking for?

like image 387
ewok Avatar asked Oct 16 '25 14:10

ewok


1 Answers

$map{key2} returns the value of the desired element. The element is a reference to a string.[1] If you wish to print the string referenced by that reference, you need to dereference it.

say ${ $map{key2} };

References:

  • Mini-Tutorial: Dereferencing Syntax
  • References quick reference
  • perlref
  • perlreftut
  • perldsc
  • perllol

  1. I doubt this is intentional! This surely indicates an error somewhere.
like image 141
ikegami Avatar answered Oct 18 '25 19:10

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!