in reply to Perl OOP Function Entrance
There are in fact only 2 cases, if $self is not being made use of in the subroutine:
For a function call, no class resolving is done, so the function must be either fully qualified or its symbol imported into the current namespace.
A method call is resolved via $class_name or $class_instance (object), and the sub gets the resolving thing as first argument.
Conflating these two into the same thing just tells that the package is not meant to be object oriented. Losing the identifier of the call makes it impossible to dispatch to another class on which this one is based.
use 5.10.0; package Animal; sub speak { my $self = shift; ref $self and $self = ref $self; say "$self says: ", $self->word; } package Cow; @Cow::ISA = qw(Animal); sub word { "moo" } package Dog; @Cow::ISA = qw(Animal); sub word { "wuff" } package main; Cow->speak; Dog->speak; __END__ Cow says: moo Dog says: wuff
If you throw away the Animal, there's no way to make it speak.
So, this is not about Perl OOO Function Entrance but adding syntactic sugar to plain function calls. For that, the following does the job:
shift if $_[0] eq __PACKAGE__ || ref $_[0] eq __PACKAGE__;
This can be added via simple filtering as the first line to the body of a subroutine.
But I concur with LanX: I consider it bad practice to do such conflation on a regular basis, since it blurs the semantic differences of the various ways to call a subroutine. If that equality of dispatching is condoned within your team, it will bite you the first time when you use really object oriented modules from a third party.
And you haven't considered other ways to call a subroutine. The following are all equivalent:use Animal; # contains Cow and Dog as above Cow->speak; speak Cow; my $animal = 'Cow'; $animal->speak; speak $animal; Animal::speak('Cow'); $animal = bless do{\my $x}, 'Cow'; Animal::speak($animal); $animal->speak;
Of all computer languages I know, perl is the most language thing. And you can make most use of a language knowing and musing about its subtleties, and expressing yourself acccordingly without blurring them.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl OOO Function Entrance
by Mano_Man (Acolyte) on Aug 28, 2017 at 17:18 UTC |