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:
In reply to Short invocation for per-object methods by Crackers2
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |