in reply to Re: File Handle questions
in thread File Handle questions

Sure, I would like to have my log handling in a module that does all my logging stuff as I neede it. Therefoe I have 3 subs in this module ... LOG_OPEN, LOG_MSG, LOG_CLOSE. I need to give the function LOG_OPEN a filename and a filehandle (that I am flexible to have more than 1 log file in a script). Now I stuck with the file handle as described. I hope this helps.

Replies are listed 'Best First'.
Re^3: File Handle questions
by stevieb (Canon) on Oct 23, 2016 at 13:59 UTC

    I'd take a bit of a different approach, and have the logging module create a default log handle internally, with a log() function that takes a message and an optional filename. If the optional filename is sent in, we create a new handle internally and log to it, otherwise we log to the default handle. Here's some code I put together very hastily as an example:

    use warnings; use strict; package Log; { sub new { my $self = bless {}, shift; my $log_file = shift; open my $fh, '>', $log_file or die $!; $self->{default_log} = $fh; return $self; } sub log { my ($self, $msg, $log) = @_; my $log_fh; if (defined $log){ # filename sent in open my $fh, '>>', $log or die $!; $log_fh = $fh; } else { # use the default fh $log_fh = $self->{default_log}; } print $log_fh "$msg\n"; } } package main; { my $log = Log->new('default.log'); $log->log('default log message'); $log->log('alternate log file msg', 'not-default.log'); }

    Default log file:

    $ cat default.log default log message

    Alternate log file:

    $ cat non-default.log alternate log file msg

    Is that kind of the idea you're after? Something along these lines prevents the user of the module of having to create and send in their own handles. If I'm off-base, just let us know.

    update: If you want the user to be able to send in their own file handle instead of just a file name, the log() method could be changed like this:

    sub log { my ($self, $msg, $log) = @_; my $log_fh; if (defined $log && ref $log ne 'GLOB'){ # filename sent in open my $fh, '>>', $log or die $!; $log_fh = $fh; } elsif (defined $log && ref $log eq 'GLOB'){ # file handle sent in $log_fh = $log; } else { # use the default fh $log_fh = $self->{default_log}; }

    ...and called like this (continuing on with the main example above):

    open my $fh, '>>', 'alternate.log' or die $!; $log->log('msg', $fh);

    /update

      Thanks for your feedback. Maybe you have the better approach.. I will test it soon. Thanks.
Re^3: File Handle questions
by fishmonger (Chaplain) on Oct 23, 2016 at 16:09 UTC

    My recommendation would be to not bother with writing your own logging subs, but instead to use one of the already written logging modules on cpan. My first choice would be Log::Log4perl

      ++. Although I did for fun and as a learning exercise, I agree wholeheartedly with fishmonger here.