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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |