Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there any practical difference between invoking a packaged subroutine using Package->sub() or creating an instance of the package and then invoking the subroutine? see below...
my $retone=Send->temp(); my $obj=new Send; my $ret=$obj->temp(); package Send; sub temp { return "temp"; } print "one, $retone, two, $ret\n";
Both return the same value. I was curious if one method was preferred over another and for what reasons.
Thanks.

Replies are listed 'Best First'.
(jeffa) Re: Calling Subs
by jeffa (Bishop) on Jan 17, 2001 at 01:35 UTC
    Yes - the first is called an class method - you do not need to instantiate an object before calling the method. Use these just for that situation - when you don't need to create a new object (waste of RAM).

    The second example is best used when you need to store state information in an object. That way, the method can do it's thing based on what the state of the object is.

    The fact that they return the same value is because it is the same function which happens to not use member variables. If that function used some member varibles that were specific to a particular instance of the class - then you would see a difference.

    Here is an example:

    #!/usr/bin/perl -w use strict; package foo; sub new { my ($class) = @_; return bless { foo => 'bar', }, $class; } sub baz { my ($self) = shift; print $self->{'foo'}, "\n"; } package main; my $obj = new foo; $obj->baz; # prints bar &foo::baz; # unitialized value warning issued
    Jeff

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    F--F--F--F--F--F--F--F--
    (the triplet paradiddle)
    
Re: Calling Subs
by chipmunk (Parson) on Jan 17, 2001 at 01:40 UTC
    In the first case, when temp() is called @_ contains ('Send'), while in the second case @_ contains ($obj). Since temp() doesn't use @_, that difference isn't significant here. However, if you have a method that needs to access instance data, you'd need to call the method on a specific instance, of course. For example:
    package Send; sub poke { my $self = shift; $self->{thingy} = 1; } sub new { return bless {}, $_[0]; } package main; my $obj = new Send; $obj->poke(); # good Send->poke(); # bad
    Really it just depends on what you want the method to do.