Subject: | How do I detect an anonymous subroutine? |
I want to detect if a variable declaration is done inside a subroutine.
So I wrote code like this:
my $insub = 0;
while( $elem = $elem->parent ) {
$insub = 1 and last if
$elem->isa("PPI::Statement::Sub");
}
This works fine for named subroutines but does not work for anonymous
subroutines. They are just PPI::Statement's.
How do I detect that a given element is an anonymous subroutine
declaration? Best I could come up with is $elem->first_element->content
eq 'sub' leading to this complete solution...
sub _is_in_subroutine {
my $elem = shift;
my $insub = 0;
while( $elem = $elem->parent ) {
if( _is_subroutine_declaration($elem) ) {
$insub = 1;
last;
}
}
return $insub;
}
sub _is_subroutine_declaration {
my $elem = shift;
return 1 if $elem->isa("PPI::Statement::Sub");
return 1 if $elem->isa("PPI::Statement") and
$elem->first_element and
$elem->first_element->content eq 'sub';
return 0;
}
A PPI::Element method to answer if an element is inside a subroutine
might be handy.