in reply to Re: Calling module function from within a blessed module
in thread Calling module function from within a blessed module
$self = shift if ref $_[0] eq __PACKAGE__;
Note that this unfortunately breaks for subclasses. Personally I prefer Scalar::Util's blessed and UNIVERSAL's isa.
use warnings; use strict; { package Foo; use Data::Dump; use Scalar::Util qw/blessed/; sub new { return bless {}, shift } sub foo { my $self = shift if ref $_[0] eq __PACKAGE__; dd 'foo', $self, \@_; } sub bar { my $self = shift if defined blessed($_[0]) && $_[0]->isa(__PACKAGE__); dd 'bar', $self, \@_; } } { package Bar; use parent -norequire, 'Foo'; } Foo::foo('a'); # ("foo", undef, ["a"]) Foo::bar('b'); # ("bar", undef, ["b"]) my $f = Foo->new(); $f->foo('c'); # ("foo", bless({}, "Foo"), ["c"]) $f->bar('d'); # ("bar", bless({}, "Foo"), ["d"]) my $g = Bar->new(); $g->foo('e'); # ("foo", undef, [bless({}, "Bar"), "e"]) - oops! $g->bar('f'); # ("bar", bless({}, "Bar"), ["f"])
Update: Added arguments to calls to make @_ more clear. Update 2: I guess in case the package name is "0", one could be doing defined blessed instead of just plain blessed, so I've updated the above, but since that's pretty unlikely, I'd say it's optional.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Calling module function from within a blessed module
by shmem (Chancellor) on Jan 02, 2021 at 16:51 UTC | |
|
Re^3: Calling module function from within a blessed module
by Bod (Parson) on Jan 02, 2021 at 16:42 UTC | |
by kcott (Archbishop) on Jan 02, 2021 at 19:37 UTC | |
by haukex (Archbishop) on Jan 02, 2021 at 19:48 UTC | |
by kcott (Archbishop) on Jan 02, 2021 at 21:31 UTC | |
by haukex (Archbishop) on Jan 03, 2021 at 10:34 UTC | |
| |
by shmem (Chancellor) on Jan 02, 2021 at 19:50 UTC | |
by LanX (Saint) on Jan 03, 2021 at 23:57 UTC |