Alyssa Low
Alyssa Low

Reputation: 103

Is there a way to do matching pattern using array in perl?

For example,

@seed = ('seed_1', 'seed_2', 'seed_3', 'seed_4);

However, in the future there could be more than seed_4. How can I make this as general as possible? Meaning I don't have to manually write the future seed_. It can be 'seed_50' or random values.

example:

$file ='text.txt';
for my $seed (@seed)
 {
   if (open my $data, "<", $file)
    {
      my $line =<$data>;
      print "ERROR: $line\n";
    }
   close $data;
}

the seed_ are actually folders in directories. So, I need to go through every seed to open the text file but I may not know the values in every seed folder. The dir are directories I need to open. I just need to read out the first line of the text.

so for example:

for my $dir (@dir){
    for my $seed (@seed)
     {
       if (open my $data, "<", $file)
        {
          my $line =<$data>;
          print "ERROR: $line\n";
        }
       close $data;
    }
}

Upvotes: 2

Views: 189

Answers (1)

zdim
zdim

Reputation: 66873

Escape possible non-"word" ASCII characters in the array elements using quotemeta, and build a pattern with them using alternation

my $pattern = join '|', map { quotemeta } @ary;

Then use this $pattern in a regex pattern

if ( $string =~ /$pattern/ ) { say $& }

to find the first of elements that matches in the $string (if any), or

while ( $string =~ /$pattern/g ) { say $& }

to iterate over all matches, etc.

Depending on the details it may be necessary to sort the array first.

Upvotes: 5

Related Questions