Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a hashref to a sub

Tags:

json

cgi

perl

My code is as follows super simplistic but I am just not getting it to work as intended.

use strict;
use warnings;
use CGI::Carp qw(fatalsToBrowser);
use CGI qw(-dubug);
use warnings;
use diagnostics;
use strict;
use JSON;
use Data::Dumper;

my $q = CGI->new;

my $data = $q->param('POSTDATA');
my $data_hash;

if (defined($data)) {
$data_hash = decode_json($data);
}

sub test {
    my $return_hash = shift;

    return \$return_hash;
}

my $return_to_print = test($data_hash);

print $q->header();
print "This is a test: \n";
print Dumper($return_to_print);

Basically I am sending json to the perl script, I decode the json into a hashref, then id like to pass that data to the test sub who just does nothing more than return it back so the cgi can print it, all while keeping its structure. So far I am unsuccessful and I am hoping someone can shed some light on how to properly write something like this.

So in the end dumper should print something like:

$VAR1 = { 'key' => 'value', 'key2' => 'value' };
like image 572
Kizzim Avatar asked Jan 31 '26 08:01

Kizzim


1 Answers

Your code boils down to

my $data_hash       = decode_json($data);
my $return_hash     = $data_hash;
my $return_to_print = \$return_hash;

It should not be a surprise that $return_hash is different than $return_to_print. You assigned a reference to a scalar to $return_to_print rather than copying its value (a refernce to a hash). You would need the following for them to be the same

my $return_to_print = $return_hash;

Which is to say you'd need the following:

return $return_hash;
like image 73
ikegami Avatar answered Feb 01 '26 23:02

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!