Unable to pass a hash as a reference in a module

I want to pass a hash link to a module. But in the module I can not return the hash.

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 look something like this:

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

How can I return the value passed to the callers? This is an old version of perl: v5.8.3

+4
source share
2 answers

In module 1, change sub printhash to:

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

When you call a method on an object like $obj->method( $param1 ), the method receives the object itself as the first parameter and $ param1 as the second parameter.

perldoc perlootut - Object Oriented Programming in a Perl Tutorial

perldoc perlobj - Perl object reference

+6
source

sub , @_ , .

, , @_, .

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

All Articles