j.goor has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks
I wrote a simple logging module (OO), that does basic writing.
Now I want to specify at initiation the output file.
My code:
sub _write { my ($self, $message, $status) = @_; my $timestamp = (strftime "%d/%m/%Y %H:%M:%S", localtime); print STDOUT $timestamp, $self->{_separator}, $status, $self->{_sep +arator}, $message, "\n"; $self; } # Constructor sub new { my $class = shift; ( bless {}, $class )->_init( {@_} ); } sub _init($) { my ($self, $args) = @_; $|=1; # Unbuffered output $self->{_rootdir} = $ENV{DIR_LOG}; # Set the rootdir + for logfiles $self->{_separator} = $$args{separator} || ' - '; # Default one spa +ce - no concatenation is possible $self->_write("$0 started... (pid $$)", 'SYSTEM'); $self; } # Methods sub notify { my ($self, $message) = @_; my $status = 'NOTIFY'; $self->_write($message, $status); }

What should I do print to the filehandle, which is set at initialisation?
It has to be passed somehow..
I did several attempts (including internet searches) but ofcoure no satisfying result, or I wont ask you Monks for help! ;-)
Rgds,
John

Replies are listed 'Best First'.
Re: Passing filehandles
by gellyfish (Monsignor) on Jan 10, 2005 at 13:51 UTC

    You can use a lexical scalar in place of a bareword filehandle:

    my $fh; open $fh, $path_to_file;
    and then you can store that $fh in your blessed thingy and do what you will with it later:
    print $fh "Test";

    /J\

Re: Passing filehandles
by gaal (Parson) on Jan 10, 2005 at 13:53 UTC
    Change _write to act on a member:

    print { $self->{_fh} } $self->{_separator}, $status, $self->{_separator}, $message, "\n";

    And modify _init to receive this filehandle somehow:

    # following the example of how you did seperator: $self->{_fh} = $args->{fh};

    To use this, pass a filehandle to the constructor. With modern perls this can be a lexical.

    open my $logger_fh, ">/tmp/log.log" or die...; my $logger = LoggerClass->new({ fh => $fh });

    You need to do some work, perhaps, to make STDOUT (or STDERR?) the default. You also have to turn on autoflushing on the correct filehandle. (But note that most filehandles, even when buffered, are line buffered on output; and since _write always appends a newline this step may not be required. YMMV.)