Search code examples
arraysperl

How to find all matches inside an array element and create a new element from every match in perl?


I'm new to perl and I have an array which has the following structure:

cat4, cat5, cat7;

ab:12, cd:43;

cat1;

cd:51;

cat6, cat12;

ab:17;

What I want to do, is iterate through each element containing "cat" and then, for every match to create a new array element which also contains the data from the next element (in order to push it to another array). For example:

cat4 ab:12, cd:43;

cat5 ab:12, cd:43;

cat7 ab:12, cd:43;

cat1 cd:51;

cat6 ab:17;

cat12 ab:17;

It's not a problem for me to concatenate my current element with the next one if it contains "cat" just once. I can't do it in case it appears two or more times though.

Here is my code:

use warnings;
use strict;

my @array1 = ("cat4, cat5, cat7", "ab:12, cd:43", "cat1", "cd:51", "cat6, cat12", "ab:17");
my @array2;

for (my $i=0; $i<array1; i++) 
{
    my $newarrayelem;
    my $currarrayelem = $array1[$i];

    if ($currarrayelem =~ m/cat\d+/gs)
    {
       $newarrayelem = $currarrayelem." ".array1[$i+1];
       $print $newarrayelem."\n";
       $push(@array2, $newarrayelem);
    }
}

print @array2;

What I always get as a result is "cat4, cat5, cat7 ab:12, cd:43", "cat1 cd:51", "cat6, cat12 ab:17".

What should I do in order to get the desired result above? Any help is greatly appreciated.


Solution

  • Your code is missing some sigils, but the idea is right. It can be even simpler: instead of using if with the match, you can use while which will return the elements one by one.

    for (my $i = 0; $i < $#array1; ++$i) {
        push @array2, "$1 $array1[ $i + 1 ]"
            while $array1[$i] =~ /(cat\d+)/g;
    }