Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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 Log.pm line +32. Compilation failed in require at 2.pl 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.


Comment on Re: Logging Singleton
Select or Download Code
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1019377]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2014-09-19 08:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (133 votes), past polls