... 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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.