Distinguishing Class and Object Methods

First let me start with the definition of class and object method

What is Class Method? – Method which is called without creating an object of class.

What is Object Method? – Method which is called by the reference of object.

In PERL there is no such disquisition, but let me tell you the same can be done by adding just three lines of code in function

sub func1 {
my $self = shift;
unless( ref $self) {                                                                  # Line 1
croak “Should call func1() with an object, not a class”;         # Line 2
}                                                                                          # Line 3
return “1”;
}

 

Advertisements

user warnings Vs #!/usr/bin/perl -w

Let me explain the difference with simple example.

I have created three files FooClass.pm,t1.pl  and t2.pl files

FooClass.pm

package FooClass;

my $a=10;

my $a=120;

1;

t1.pl

use strict;

use warnings;

use FooClass;

my $b = 10;

my $b = 200;

 Error message:

“my” variable $b masks earlier declaration in same scope at perl_bp.pl line 6.

t2.pl

#!/usr/bin/perl -w

use strict ;

use warnings;

use FooClass;

my $b = 100;

my $b = 200;

Error message: 

“my” variable $a masks earlier declaration in same scope at FooClass.pm line 3.

“my” variable $b masks earlier declaration in same scope at perl_bp.pl line 7.

So the difference is scope of two statements to find bugs in perl program.

-w turns on warning for the whole Perl program, including any included modules etc; ‘use warnings’ enables them only in the current lexical scope.