这个问题与
How can I find all the methods that contain a specific string within a Perl codeset?松散相关.
在处理这个问题时,Hakon有用地建议我看一下PPI
.
PPI引起了我的兴趣,作为一种学习练习,我一直在尝试使用它来传递文件并在文件中查找包含特定字符串的方法.
PPI很大且功能丰富,我坚持在子程序中搜索的最佳方式.我既坚持对PDOM的理解,也是寻找字符串的最佳方法
到目前为止,我有:
#The file to parse open(my $fh,'<:encoding(UTF-8)',$filename) or die "Could not open file '$filename' $!"; #Read in the entire file (they're not that large). my $src = do { local $/; <$fh> }; # Load a document my $doc = PPI::Document->new( \$src ); my $subs_ref = $doc->find( sub { $_[1]->isa('PPI::Statement::Sub') }); #Test I actually have the subs print their names... my @sub_names = map { $_->name } @$subs_ref; warn "@sub_names"; # This is where I get stuck. Do I now use PPI::Find? my $result = $subs_ref->find( \&wanted ); #What does wanted contain? #I can see I now have PDOM objects created for individual subroutines within file my $sub = $subs_ref->[0]; warn "name is " . $sub->name; warn Dumper $sub;
使用上面我可以看到我已经解析了文件并且可以访问文件中每个子例程的PDOM对象.
PDOM对象的示例如下所示:
$VAR1 = bless( { 'children' => [ bless( { 'content' => 'sub' },'PPI::Token::Word' ),bless( { 'content' => ' ' },'PPI::Token::Whitespace' ),bless( { 'content' => 'Welcome' },bless( { 'finish' => bless( { 'content' => '}' },'PPI::Token::Structure' ),'start' => bless( { 'content' => '{' },'children' => [
我正在搜索可能包含在双引号或单引号内的字符串.例如:
bless( { 'separator' => '"','content' => '"signup/welcome_$user_type"' },'PPI::Token::Quote::Double' ),
我的问题:
在$subs_ref-> [i]中搜索“注册/欢迎”的最佳方法是什么?我是否使用PPI :: Find(如果是的话,你能给我一个例子吗?)还是有更好的方法?
解决方法
您可以尝试使用例如迭代每个子例程的所有PPI :: Token :: Quote :: Double:
my @result = map {[ $_->name,$_->find( 'PPI::Token::Quote::Double' )] } @$subs_ref; for my $elem (@result) { say $elem->[0]; my $found = 0; for my $node ( @{$elem->[1]} ) { my $str = $node->content; $found = 1 if $str =~ "signup/welcome"; } say "-->" . ($found ? "found" : "not found"); }