user3544092 user3544092 - 3 months ago 7
Perl Question

Filter group of pattern inside array in perl

How do I filter and collect a group of pattern inside array using regex ?

search pattern is

.include 'pathToFile'
where
pathToFile
have to be stored into
@include
array.

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


Unfortunately my code doesn't store only
$4
which is the include file path. How can I make it work?

Answer

You need to map each item in the @fileContent to the capture $4 and only then grep to find only matching ones:

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

By the way, the first three capture groups are redundant, so you may rewrite the regex with only capture group $1:

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