Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub routine reference is not working

Tags:

perl

I am learning subroutine reference. I written a code but it is not working

use strict;
use warnings;
sub test1 {
#$arg = shift;
print "arg";
}

sub test2 {
return \&test1;
}

&test2;

Output is nothing. Any thoughts why my code is not working.

like image 557
Sumit Avatar asked Jun 15 '26 11:06

Sumit


2 Answers

&test2 does almost the same as test2(). It runs test2, which returns the reference to test1, but does not run it. You have to dereference the reference to call the referenced code:

test2->();

Or even

test2()->();
like image 88
choroba Avatar answered Jun 18 '26 01:06

choroba


First of all,

&test2;

is a poor way of calling a subroutine. Don't use & if you don't even know what it does! That should be

test2;

or

test2();

On to your problem: You never call the returned subroutine!

test2()->();
like image 39
ikegami Avatar answered Jun 17 '26 23:06

ikegami



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!