Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: Logging Singleton

by 7stud (Deacon)
on Feb 18, 2013 at 17:26 UTC ( #1019377=note: print w/replies, xml ) Need Help??

in reply to Logging Singleton

Please let me know if there is a better way or a perferred method.

  1. Rename new() to get_logger()?
  2. Use a closure?
  3. use strict; use warnings; use 5.012; package Log; { my $logger; sub get_logger { if (not $logger) { my ($class, $path) = @_; say "Creating logger..."; $logger = {}; bless $logger, "Log"; $logger->create_logfile($path); } else { say "Logger already exists..." } return $logger; } } sub create_logfile { } sub do_stuff { #$logger = 'hello'; }
    use strict; use warnings; use 5.012; use Log; my $log = Log->get_logger(); #Creating logger... $log = Log->get_logger(); #Logger already exists... $log = Log->get_logger(); #Logger already exists... #$log->do_stuff;

    With a closure, you can't (mistakenly) change the $logger singleton in another subroutine:

    Global symbol "$logger" requires explicit package name at line +32. Compilation failed in require at line 5.

    The my variable $logger ceases to exist after the end of the block, and thereafter only the sub get_logger() can see the $logger variable.

Replies are listed 'Best First'.
Re^2: Logging Singleton
by Anonymous Monk on Feb 18, 2013 at 19:34 UTC
    Thank you. Haven't implemented a closure before but I'll read up on them. Thanks!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1019377]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2018-03-25 04:22 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (300 votes). Check out past polls.