Trouble recording unique regex output to array in perl

Posted by Structure on Stack Overflow See other posts from Stack Overflow or by Structure
Published on 2010-03-12T10:07:27Z Indexed on 2010/03/12 10:27 UTC
Read the original article Hit count: 136

Filed under:

The goal of the following code sample is to read the contents of $target and assign all unique regex search results to an array.

I have confirmed my regex statement works so I am simplifying that so as not to focus on it.

When I execute the script I get a list of all the regex results, however, the results are not unique which leads me to believe that my manipulation of the array or my if (grep{$_ eq $1} @array) { check is causing a problem(s).

#!/usr/bin/env perl

$target = "string to search";

$inc = 0;
$once = 1;

while ($target =~ m/(regex)/g) { #While a regex result is returned
        if ($once) { #If $once is not equal to zero
                @array[$inc] = $1; #Set the first regex result equal to @array[0]
                $once = 0; #Set $once equal to zero so this is not executed more than once
        } else {
                if (grep{$_ eq $1 } @array ) { #From the second regex result, check to see if the result is already in the array
                        #If so, do nothing
                } else {
                        @array[$inc] = $1; #If it is not, then assign the regex search result to the next unused position in the array in any position.
                        $inc++; #Increment to next unused array position.
                }
        }
}

print @array;

exit 0;

© Stack Overflow or respective owner

Related posts about perl