Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Declaring a code ref with arguments

by BrowserUk (Patriarch)
on Aug 05, 2003 at 09:13 UTC ( [id://280929]=note: print w/replies, xml ) Need Help??


in reply to Declaring a code ref with arguments

The simple answer is that you cannot store a coderef with arguments. What would that mean if you could?

sub test{ print @_; } ## THIS DOESN'T WORK, BUT IF IT DID... my $coderef = \&test( 'this is the argument' ); $coderef->(); # would print 'this is the argument' ); $coderef->( 'a different argument' ); # Would print 'this is the argument'!!

If you really want the sub to always have the same argument(s), then they aren't argument(s)--they are constant(s) :) -- so code the sub that way.

sub test{ print 'this is the argument'; } my $coderef = \&test; $coderef->(); # prints 'this is the argument' ); $coderef->( 'a different argument' ); # Prints 'this is the argument'!!

Problem solved:)

However, if you want to pass different arguments when you invoke the coderef, do so.

my $coderef = sub{ print @_; }; $coderef->( 'Some', 'args' ); # Prints 'someargs'

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
If I understand your problem, I can solve it! Of course, the same can be said for you.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://280929]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (3)
As of 2024-04-24 00:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found