in reply to Logging Singleton
Please let me know if there is a better way or a perferred method.
- Rename new() to get_logger()?
- Use a closure?
- Comment on Re: Logging Singleton
- Select or Download Code
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.
Replies are listed 'Best First'. | |
---|---|
Re^2: Logging Singleton
by Anonymous Monk on Feb 18, 2013 at 19:34 UTC |
In Section
Seekers of Perl Wisdom