... print $log ; gives HASH(0x1e2ec5c)
It should print "Test_logger=HASH(0x1e2ec5c)", i.e. the stringified representation of an object reference would normally include the package name. The fact that it doesn't, in your case, makes me think that maybe you forgot to bless the hash in the constructor?
Here's a simple example that should work the way (I think) you're expecting:
___ Test_logger.pm ___
package Test_logger; sub new { my $pkg = shift; my $self = { logfile => "/tmp/test_logger.log", # default @_ # merge in user-specified attributes }; open my $fh, ">", $self->{logfile} or die "Cannot open logfile '$s +elf->{logfile}': $!"; $self->{logfh} = $fh; return bless $self, $pkg; } sub message { my $self = shift; my $msg = shift; my $fh = $self->{logfh}; print $fh "$msg\n"; } 1;
___ main program ___
#!/usr/bin/perl use strict; use warnings; use Test_logger; sub test_addition { my $log = shift; $log->message("Inside the subroutine test_addition"); } my $log = Test_logger->new( logfile => "my.log" ); $log->message("Start of program"); test_addition($log);
Of course, you can similarly pass $log to any subroutine defined in other modules as well...
In reply to Re: how to pass object to a subroutine
by almut
in thread how to pass object to a subroutine
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |