use strict; use warnings; use PPI; use PPI::Dumper; # retrieve the example standalone script from DATA my $doc; while (){ $doc .= $_} my $pdom = PPI::Document->new( \$doc ); # uncomment to see the whole pdom #PPI::Dumper->new($pdom)->print; $pdom->find( sub{ # skip white spaces, for example return if $_[1]->isa('PPI::Token::Whitespace'); # just print top level elements if ( # is a top level element $_[1]->parent == $pdom ){ # PPI class remove \n at the end starting line print "found TOPLEVEL ",ref $_[1]," ", $_[1]=~s/\n$//r ," (line ",$_[1]->line_number,")\n"; } } ); __DATA__ #!/usr/bin/env perl my $fb = fizzbuzz(); print "$_\n" for @$fb; sub fizzbuzz { my ($n, $m) = (1, 100); my @out; for my $num ($n .. $m) { my $line = ''; $line .= 'fizz' if $num % 3 == 0; $line .= 'buzz' if $num % 5 == 0; push @out, $line || $num; } return \@out; } #### found TOPLEVEL PPI::Token::Comment #!/usr/bin/env perl (line 1) found TOPLEVEL PPI::Statement::Variable my $fb = fizzbuzz(); (line 3) found TOPLEVEL PPI::Statement print "$_\n" for @$fb; (line 4) found TOPLEVEL PPI::Statement::Sub sub fizzbuzz { my ($n, $m) = (1, 100); my @out; for my $num ($n .. $m) { my $line = ''; $line .= 'fizz' if $num % 3 == 0; $line .= 'buzz' if $num % 5 == 0; push @out, $line || $num; } return \@out; } (line 6)