2

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;
5
  • Is the order of the result in the array important to you? Commented Mar 12, 2010 at 10:31
  • 1
    The problem with your code is the order of $inc++ and @array[$inc]=$1 Commented Mar 12, 2010 at 10:35
  • 1
    Not related to your problem, but @array[$inc] = $1 is a mistake -- you meant $array[$inc] = $1. The version you wrote only works "by accident". Commented Mar 12, 2010 at 12:18
  • If there is a way to sort the results of the hash, that would be beneficial as well, but not a hard requirement for what I am doing. Thanks for all the feedback! Very sinsightful. Commented Mar 12, 2010 at 14:57
  • Hi Structure: please see the updated version if you want to preserve the order of the results. Commented Mar 12, 2010 at 16:08

1 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Fantastic! It works and you simultaneously reduced my bloated code to three lines! Why is a hash better than an array in this case?
I still have a way to go I guess. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.