http://www.perlmonks.org?node_id=994905


in reply to Converting scalar value to hash

philipbailey's explanation is good but let me put this in other words.

Your $r->print() method receives an HashRef. HashRefs looks like this:

my $hashref = { 'key' => 'value' };

A real Hash looks like this:

my %hash = ('key1' => 'value1', 'key2' => 'value2');

You can also do this:

my %hash = ('key1', 'value1', 'key2', 'value2');

With the same result. You basically populate your Hash using a list.

You already know that if you pass a list to a method, you receive the same elements in the @_ variable. But if you pass this: { 'key' => 'value' } to your method, it will receive a HashRef (in the first element of @_), a reference to a hash, so if you print it in scalar mode, you effectively print the reference address.

What you want to do in your method, to print the content of the HashRef and not the address, you have to "dereference" it. Read perlref for more details.

Now, here is a short example. Imagine your print method:

sub print { my $self = shift; my ($hashref) = @_; # print the reference address: print $hashref; # dereference the hashref and print the content: print %{$hashref}; }

Here your method receives a HashRef, but if you want your method to receive a Hash, you can change the way you pass your arguments:

$r->print( %{ 'response' => {'result' => $results,}, });

Personally, I would not do that. I would pass the HashRef and dereference on the other side. Now if you are stuck with your content in a real hash and you want to pass it to the same method, you have to pass its reference, like this:

my %real_hash = ( 'response' => {'result' => $results} ); # Passing the reference of a real hash $r->print( \%real_hash );
There are no stupid questions, but there are a lot of inquisitive idiots.