tags:

views:

70

answers:

1

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;
+6  A: 

how about this:

while ($target =~ m/(regex)/g) {
   $hash{$1}++;
}
print keys %hash;

Update:

# if the order matters
while ($target =~ m/(a.)/g) { 
    $hash{$1} = ++$i unless $hash{$1};
}
@array = sort {$hash{$a} <=> $hash{$b}} keys %hash;
xiechao
Fantastic! It works and you simultaneously reduced my bloated code to three lines! Why is a hash better than an array in this case?
Structure
A hash's key is unique
ccheneson
I still have a way to go I guess. Thanks!
Structure
Thank you again!
Structure