在perl中过滤数组内的模式

时间:2016-08-22 13:57:09

标签: arrays regex perl filter

如何使用正则表达式过滤和收集数组内的一组模式?

搜索模式为.include 'pathToFile',其中pathToFile必须存储到@include数组中。

my @include = grep {$4 if /^\s*\.(inc)(l(ude)?)?\s+'(\S+)'/i} @fileContent;

不幸的是,我的代码不仅仅存储$4这是包含文件路径。我怎样才能使它发挥作用?

1 个答案:

答案 0 :(得分:0)

您需要map @fileContent中的每个项目$4,然后grep才能找到匹配的项目:

my @include = grep {!/^$/} map {/^\s*\.(inc)(l(ude)?)?\s+'(\S+)'/i && $4} @fileContent;

顺便说一下,前三个捕获组是多余的,因此您可以仅使用捕获组$1重写正则表达式:

my @include = grep {!/^$/} map {/^\s*\.inc(?:l(?:ude)?)?\s+'(\S+)'/i && $1} @fileContent;
相关问题