The fact that your sample text shows "world!" twice proves that bar() is not truly "inside" foo(). The normal scope rules do not come into play.

If you truly want to keep a lexical sub, you should build it into a coderef:
sub foo { my $bar = sub { print "world!\n" }; print "Hello\n"; &$bar; #also can be written as: $bar->(); } foo(); #&$bar here will not work since $bar is only valid inside foo.
update: Please note that there are some great examples of using nested subs to create closures, especially a great example on using this technique to create a static variable. This can be very useful if a certain sub should set a global value once and only once, so it computes the value and then creates an accessor routine that refers to the variable.

Although stylistically I think you'd only want to do this if you were going to create a bunch of them (as in tilly's masterful Why I Like Functional Programming). Having a bunch of closures running around could make it hard to remember what's where and why. :)

In reply to (ichimunki) Re: Sub Definitions Within Subs: Best Way to Exploit by ichimunki
in thread Sub Definitions Within Subs: Best Way to Exploit by crazysniffable

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.