Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Defining a sub within a sub: OK?

by AnomalousMonk (Archbishop)
on Oct 14, 2009 at 22:27 UTC ( [id://801226]=note: print w/replies, xml ) Need Help??


in reply to Defining a sub within a sub: OK?

As the example below shows, defining a subroutine with sub within another subroutine and then calling it from within the enclosing subroutine works (although I don't think it's considered quite kosher), but really buys you nothing because the enclosed subroutine is still global in scope.

I have seen the trick on PM of local-izing a glob within a subroutine and then defining a named subroutine via that glob, but otherwise the approach for private subroutines seems to be to use anonymous subs defined within a sub.

The statement  my sub foo { ... } produces a  "my sub" not yet implemented ... error in 5.10 (and before AFAIR), so someone is thinking about this!

>perl -wMstrict -le "print level2(); sub level1 { sub level2 { return 'level2(): foo' } print 'level1(): ', level2(); } level1(); print level2(); " level2(): foo level1(): level2(): foo level2(): foo
Updates:
  1. After reading Joost's reply, I remembered the 'stupid local trick' referred to above. Perhaps someone else can say if this approach differs at all (other than by supplying a local named subroutine) from the anonymous-subroutine-assigned-to-lexical-variable approach; I can see no difference.
    >perl -wMstrict -le "sub level1 { my $x = shift || 'default'; local *foo = sub { return 'foo' . $x }; print foo(); } level1('bar'); level1(); foo(); " foobar foodefault Undefined subroutine &main::foo called at -e line 1.
  2. A 'stupid local trick'? Well, maybe not. See ikegami's detailed reply to Re^3: Defining a sub within a sub: OK? below: there is an advantage.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-19 02:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found