Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Converting scalar value to hash

by greengaroo (Hermit)
on Sep 21, 2012 at 13:32 UTC ( #994905=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: Converting scalar value to hash
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://994905]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (8)
As of 2014-08-23 08:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (173 votes), past polls