Forum Moderators: coopster & phranque

Message Too Old, No Replies

dual nature of a method

dual nature of a method

         

kashyap_nd

6:41 pm on Mar 29, 2004 (gmt 0)

10+ Year Member



Hi All,

How can i write a method which will behave as a class method as well instance method?

Thanks
Nand

kashyap_nd

8:15 pm on Mar 29, 2004 (gmt 0)

10+ Year Member



I tried this.

sub dual {
my ($self,$time);
if (ref($_[0]) ) {
($self,$time) = @_;
}else {
($time) = @_;
}
blah blah ..........
}

The only problem with the above method is that it will not work properly if the first argument to it is a reference. Is there any ohter way to make it a class method as well instance method.

Thanks
Nand

SeanW

9:02 pm on Mar 30, 2004 (gmt 0)

10+ Year Member



Rather than simply checking if $_[0] is a reference, compare it to the reference you'd be expecting if it were already blessed.

[perl]
if ($_[0] =~ /Foo::Bar/) {
[/perl]

Sean

kashyap_nd

10:02 pm on Mar 31, 2004 (gmt 0)

10+ Year Member



What will happen in case of inheritance?
The package name Foo::Bar shouldn't be hardcoded.

Can I simply check if it is an object reference
and not other kind of reference.If yes how?

SeanW

10:22 pm on Mar 31, 2004 (gmt 0)

10+ Year Member



Hrm... Good point.

Have a look at the UNIVERSAL class, everyone derives from it implicitly, and it provides some functions. I believe you can use it to walk the inheritance tree, or at the least, differentiate between an object reference as opposed to a regular variable. The camel book has a few pages on it, or search the web.

Sean