Perl is not Pascal. :-) Nested functions are syntactically possible, but not really supported as a style of coding. The solution borisz gave works, but you instantiate two new closures every time the function is called — a lot of wasted effort.

Why don't you simply write utility functions and pass the parameters out to them?

sub my_func { my ( $self, $ptr_array, $value ) = @_; return look_right( $ptr_array, $value ) if ( $value == 0 ); return look_left( $ptr_array, $value ) if ( $value == @{ $ptr_arr +ay } ); return ( look_right( $ptr_array, $value ) && look_left( $ptr_array, $value ) ); } sub look_left { my ( $ptr_array, $value ) = @_; # ... } sub look_right { my ( $ptr_array, $value ) = @_; # ... }

The other alternative, if for some reason you really don't want to pass parameters, would be to use a naked block to share the variables among functions:

{ my ( $ptr_array, $value ); sub my_func { my $self; ( $self, $ptr_array, $value ) = @_; return look_right() if ( $value == 0 ); return look_left() if ( $value == @{ $ptr_array } ); return ( look_right() && look_left() ); } sub look_left { ... } sub look_right { ... } }

One side comment: please don't use prototypes unless there's a real reason to. Of which there are very few, none of which the code you show is indicative of. For your own benefit, please read Far More Than Everything You've Ever Wanted to Know about Prototypes in Perl.

Makeshifts last the longest.


In reply to Re: Nested subroutines and access to variables in an outer scope by Aristotle
in thread Nested subroutines and access to variables in an outer scope by PerlingTheUK

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.