使用perl PPI在子例程中查找字符串
发布时间:2020-12-16 06:13:44 所属栏目:大数据 来源:网络整理
导读:这个问题与 How can I find all the methods that contain a specific string within a Perl codeset?松散相关. 在处理这个问题时,Hakon有用地建议我看一下 PPI . PPI引起了我的兴趣,作为一种学习练习,我一直在尝试使用它来传递文件并在文件中查找包含特定字
|
这个问题与
How can I find all the methods that contain a specific string within a Perl codeset?松散相关.
在处理这个问题时,Hakon有用地建议我看一下 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' ),
我的问题: 解决方法
您可以尝试使用例如迭代每个子例程的所有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");
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
