Created
July 1, 2012 22:40
-
-
Save ynonp/3029901 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Logger; | |
use Moose; | |
has 'fout', is => 'ro', lazy_build => 1; | |
has 'filename', is => 'ro'; | |
sub _build_fout { | |
my $self = shift; | |
my $fh; | |
if ( $self->filename ) { | |
open $fh, '>', $self->filename; | |
} else { | |
$fh = *STDOUT; | |
} | |
return $fh; | |
} | |
sub log { | |
my $self = shift; | |
my $fh = $self->fout; | |
print $fh @_, "\n"; | |
} | |
sub DEMOLISH { | |
my $self = shift; | |
close $self->fout if $self->fout; | |
} | |
package main; | |
# Dependency injection | |
my $test; | |
open my $fake_fout, '>', \$test; | |
my $l2 = Logger->new( fout => $fake_fout ); | |
$l2->log("Hello"); | |
die "Fail" if $test ne "Hello\n"; | |
close $fake_fout; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment