eniosp
eniosp

Reputation: 43

Cannot get hash passed as reference in a module

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

Upvotes: 4

Views: 117

Answers (2)

xxfelixxx
xxfelixxx

Reputation: 6602

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

Upvotes: 6

Quentin
Quentin

Reputation: 943615

When you call a sub as a method, the first value in @_ will be the object you called it on.

The first argument you pass to it will be the second value in @_, which you are currently ignoring.

sub printhash {
    my ($self, $h) = @_;

Upvotes: 6

Related Questions