Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl module class method vs ordinary subroutine

Tags:

perl

So I was wondering if there is any difference in usage between a Perl class method and an ordinary subroutine from a standard module. Is there a time you would use one over the other? For this example, I'm assuming that no object methods are present in either module.

Quick little main class here:

#!/usr/local/bin/perl

use strict;
use warnings;

use Foo;
use Bar;

my $arg1 = "blah";
my ($str1, $str2);

$str1 = Foo::subroutine($arg1);
$str2 = Bar->subroutine($arg1);
exit(0);

Package Foo would hold my ordinary subroutine call

use strict;
use warnings;

package Foo;

sub subroutine {
    my $arg = shift;
    my $string = "Ordinary subroutine arg is $arg\n";
    return $string;
}
1;

Package Bar would hold my class method call

use strict;
use warnings;

package Bar;

sub subroutine {
    my $class = shift;
    my $arg = shift;
    my $string = "Class method arg is $arg\n";
    return $string;
}
1;

Normally if I'm writing Perl code, I would just use the class method option (like with the Bar example), but I started pondering this question after reading some code from a former coworker that used the syntax like in the Foo example. Both seem to do the same thing inherently, but there seems to be more than meets the eye.

like image 960
MeNoSeeGood Avatar asked Feb 20 '15 17:02

MeNoSeeGood


1 Answers

The decider is whether your Module is an object-oriented module or not.

  • If Module is simply a container for a collection of subroutines, then I would expect it to use Exporter and offer the opportunity to import a subset of its subroutines into the calling name space. An example is List::Util

  • On the other hand, if there is a constructor Module::new, and the intention is to use it in an OO manner, then you shouldn't mix simple subroutines in with methods (except perhaps for private subroutines that the module uses internally). An example is LWP::UserAgent

So I would expect the sources to be written like one or the other of these, and not a mixture in between. Of course there are always circumstances where a rule of thumb should be ignored, but nothing comes to mind in this case.

Foo.pm

use strict;
use warnings;

package Foo;

use Exporter 'import';
our @EXPORT_OK = qw/ subroutine /;

sub subroutine {
    my ($arg)  = @_;
    "Ordinary subroutine arg is $arg\n";
}

1;

Bar.pm

use strict;
use warnings;

package Bar;

sub new {
  my $class = shift;
  bless {}, $class;
}

sub subroutine {
    my $class = shift;
    my ($arg) = @_;
    "Class method arg is $arg\n";
}

1;

main.pl

#!/usr/local/bin/perl

use strict;
use warnings;

use Foo 'subroutine';
use Bar;

my $arg1 = "blah";

print subroutine($arg1);
print Bar->subroutine($arg1);

output

Ordinary subroutine arg is blah
Class method arg is blah
like image 72
Borodin Avatar answered Oct 05 '22 18:10

Borodin