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.

In reply to Re: Defining a sub within a sub: OK? by AnomalousMonk
in thread Defining a sub within a sub: OK? by talexb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.