Crackers2 has asked for the wisdom of the Perl Monks concerning the following question:
I have a class, and I want to be able supply it with a debug sub for printing debug messages, on a per-object basis.
My first implementation looks something like this:
package test; use strict; use warnings; sub new { my ($class, %params) = @_; my $self = { debug => sub {}, %params }; bless $self, $class; return $self; } sub method1 { my ($self) = @_; $self->{'debug'}->("Entering method1"); } package main; use strict; use warnings; my $t1 = test->new( debug => sub { print STDERR "debug: @_\n"; } ); my $t2 = test->new( debug => sub { print STDERR "DEBUG: @_\n"; } ); $t1->method1; $t2->method1;
This works fine, but I'm rather lazy and would prefer to avoid the long $self->{'debug'}->("text") invocation for each debug message. I'd prefer to be able to just say debug("text") and have it DWIM.
So I changed the code to this:
package test; use strict; use warnings; our $self; sub debug { $self->{'debug'}->(@_); } sub new { my ($class, %params) = @_; my $self = { debug => sub {}, %params }; bless $self, $class; return $self; } sub method1 { local ($self) = @_; debug "Entering method1"; } package main; use strict; use warnings; my $t1 = test->new( debug => sub { print STDERR "debug: @_\n"; } ); my $t2 = test->new( debug => sub { print STDERR "DEBUG: @_\n"; } ); $t1->method1; $t2->method1;
Which seems to do the trick.
So now I have two questions:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Short invocation for per-object methods
by perrin (Chancellor) on Jan 04, 2007 at 05:33 UTC | |
by Crackers2 (Parson) on Jan 04, 2007 at 06:56 UTC | |
by perrin (Chancellor) on Jan 04, 2007 at 15:45 UTC | |
by ikegami (Patriarch) on Jan 04, 2007 at 16:37 UTC | |
by perrin (Chancellor) on Jan 04, 2007 at 16:47 UTC | |
|
Re: Short invocation for per-object methods
by ikegami (Patriarch) on Jan 04, 2007 at 06:40 UTC | |
by Crackers2 (Parson) on Jan 04, 2007 at 07:14 UTC | |
|
Re: Short invocation for per-object methods
by osunderdog (Deacon) on Jan 04, 2007 at 12:52 UTC | |
|
Re: Short invocation for per-object methods
by tinita (Parson) on Jan 04, 2007 at 11:03 UTC | |
|
Re: Short invocation for per-object methods
by pajout (Curate) on Jan 04, 2007 at 13:02 UTC |