user3544092 user3544092 - 6 months ago 14
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'
have to be stored into

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

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


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;