Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module reference passed in call to module method

Tags:

perl

I have a perl script called fetch.pl and a module called My_Util.pm.

My_Util.pm

package My_Util;

sub get_header
{
    my $msg = shift;
    return " ===== $msg ===== ";
}

1; # Perl modules must return a true value when loaded.

fetch.pl

use My_Util;

print_and_log(My_Util->get_header("foo"));
print_and_log("blah");

sub print_and_log
{
    my $message = shift;
    print("$message\n");
}

Expected Output:

===== foo =====
blah

Actual Output:

===== My_Util =====
blah

Edit: Fixed syntax errors

like image 357
ErikusMaximus Avatar asked Jun 16 '26 17:06

ErikusMaximus


1 Answers

The ->get_header syntax is that for a method call. A method call passes the invocant (i.e. the object or class name) as an implicit first argument.

So, assuming we have

package MyUtil;
sub foo {}

somewhere, the call

MyUtil->foo(1, 2, 3)

ends up doing MyUtil::foo("MyUtil", 1, 2, 3).

Of course you can call

MyUtil::foo(1, 2, 3)

directly without passing any implicit arguments.

See also perldoc perlobj.

Another difference is that the :: version does a normal function call, whereas the -> version does a method call, which also follows inheritance, i.e. with MyUtil->foo there need not be a MyUtil::foo sub at all if MyUtil inherits from a class that provides a foo method.

like image 64
melpomene Avatar answered Jun 23 '26 00:06

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!