Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get hash passed as reference in a module

Tags:

hash

perl

I want to pass a hash reference to a module. But, in the module, I am not able to get the hash back.

The example:

#!/usr/bin/perl
#code.pl
use strict;
use Module1;

my $obj = new Module1;

my %h = (
    k1 => 'V1'
);

print "reference on the caller", \%h, "\n";

my $y = $obj->printhash(\%h);

Now, Module1.pm:

package Module1;
use strict;
use Exporter qw(import);
our @EXPORT_OK = qw();
use Data::Dumper;

sub new {
    my $class = $_[0];
    my $objref = {};
    bless $objref, $class;
    return $objref;
}


sub printhash {
    my $h = shift;

    print "reference on module -> $h \n";
    print "h on module -> ", Dumper $h, "\n";
}
1;

The output will be something like:

reference on the callerHASH(0x2df8528)
reference on module -> Module1=HASH(0x16a3f60)
h on module -> $VAR1 = bless( {}, 'Module1' );
$VAR2 = '
';

How can I get back the value passed by the caller? This is an old version of perl: v5.8.3

like image 537
eniosp Avatar asked Dec 15 '22 06:12

eniosp


1 Answers

In Module1, change sub printhash to:

sub printhash {
    my ($self, $h) = @_;
    # leave the rest
}

When you invoke a method on a object as $obj->method( $param1 ) the method gets the object itself as the first parameter, and $param1 as the second parameter.

perldoc perlootut - Object-Oriented Programming in Perl Tutorial

perldoc perlobj - Perl Object Reference

like image 190
xxfelixxx Avatar answered Jan 11 '23 20:01

xxfelixxx