Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Subroutine reference

by vinoth.ree (Monsignor)
on Mar 13, 2009 at 04:30 UTC ( [id://750309]=perlquestion: print w/replies, xml ) Need Help??

vinoth.ree has asked for the wisdom of the Perl Monks concerning the following question:

sub testing(){ foreach(@_){ print $_; } } my $subref=\&testing(1,2,3,4,6); print Dumper $subref; my $subref=\&testing;

In the above code I tried to get the reference to a subroutine, When I try the first one with parameter it called the function and the return value's reference is saved in the $subref variable

In the second one I tried without parameter the subroutine's reference saved in the $subref variable

How these two interpreted differently in Perl?

Replies are listed 'Best First'.
Re: Subroutine reference
by ikegami (Patriarch) on Mar 13, 2009 at 05:15 UTC

    In the second, you have the reference operator followed by a subroutine name. This returns a reference to the named subroutine.

    In the first, you have the reference operator followed by a subroutine call. Subroutine calls evaluate to the value returned by a call to the subroutine. You're making a reference to that.

    The solution is to wrap the call in a subroutine that takes no argument, and take a reference to that subroutine instead.

    my $subref = sub { testing(1,2,3,4,6) };
Re: Subroutine reference
by lakshmananindia (Chaplain) on Mar 13, 2009 at 04:45 UTC
    sub greet { print "hello \n"; } $rs = \&greet; # Create a reference to subroutine greet $rs = \&greet();
    It calls greet and produces a reference to its return value.
    --Lakshmanan G.

    Your Attempt May Fail, But Never Fail To Make An Attempt

Re: Subroutine reference
by nagalenoj (Friar) on Mar 13, 2009 at 04:45 UTC
    Dear monk,

    It is not okay to use parentheses when taking a subroutine reference. So, avoid that statement.

    Subroutine references
Re: Subroutine reference
by Anonymous Monk on Mar 13, 2009 at 07:22 UTC
    B::Deparse can be illuminating
    $ perl -MO=Deparse,-p temp.pl sub testing () { foreach $_ (@_) { print($_); } } (my $subref = \(&testing(1, 2, 3, 4, 6))); print(Dumper $subref); (my $subref = (\&testing)); __DATA__ temp.pl syntax OK

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://750309]
Approved by ikegami
Front-paged by jonnyfolk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-03-29 09:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found