Typically package methods are only useful when creating a new object that might rely on inheritance. If you create a descendent object, and simply want to inherit the parent's "new" constructor, simply using bless without a second argument will cause the new object to be blessed into the parent class. Providing that first argument to the 'new' method and passing it as the second argument to bless causes it to be blessed into the class that your code originally used. Similarly, using ref as above allows you to create new objects via a pre-existing object ($self->new).package A::B; sub new { my $caller = shift; my $self = {}; bless $self, ref($caller) || $caller; } sub method { my $self = shift; my @args = @_; print "self=$self, args=@args\n"; } sub function { my @args = @_; print "args=@args\n"; } package main; $self = new A::B; # A::B::new as a package method, # first arg = "A::B"; $self = A::B->new; # A::B::new as a package method, # first arg = "A::B"; $self = $self->new; # A::B::new as an *object* method, # first arg = $self, ref($self) = "A::B" &A::B::function("some", "args"); # don't care about $self or A::B $self->method("some", "args"); # Need to know $self &A::B::method($self, "some", "args"); # Same results, weird methodolog +y A::B->method("some", "args"); # Need to know name of package
Other than that, the only reason you might want to use a package method is for readability.
In reply to RE: RE: Calling a class method name in a scalar using :: syntax
by Fastolfe
in thread Calling a class method name in a scalar using :: syntax
by metaperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |