Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re^2: Is it possible to create a sub exclusive to a sub?

by FoxtrotUniform (Prior)
on Sep 19, 2004 at 02:27 UTC ( [id://392090]=note: print w/replies, xml ) Need Help??


in reply to Re: Is it possible to create a sub exclusive to a sub?
in thread Is it possible to create a sub exclusive to a sub?

Yes, stacks of nested subs are super-cool. But, uh, why bother writing all recursive code this way? I don't see any gain in efficiency (if anything, creating all those subs might slow things down a tad), and it introduces an extra level of "WTF?" to people reading the code.

On the other hand, if you're writing tail-recursive code, this is a great way of not exposing an accumulator variable to the rest of the world. For example (untested):

sub fact { my $fact_tr; # needs to exist before it gets assigned to $fact_tr = sub { my ($v, $r) = @_; return 1 if $v < 2; # oversimplified $fact_tr->($v-1, $v * $r); }; # thanks ihb for pointing out the missing semi $fact_tr->(@_, 1); }
Also, have a look at Just Another Godel, Escher, Bach hacker.

Edit: Separated declaration and use of $fact_tr. Thanks ihb!

--
F o x t r o t U n i f o r m
Found a typo in this node? /msg me
% man 3 strfry

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (9)
As of 2024-04-19 07:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found