Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two regex with an If-Statement fails

I want to compare two regex in perl but it fails:

Use of uninitialized value in numeric eq <==> at [... datafile & row]. Argument [different regex!] isn't numeric in numeric eq <==> [...]

I want to store a regex in an array, when the value doesn't already exists. Therefore I compare the current regex (tmpvar) with all elements in the array.

Is it possible in general or do I have to use a work-around?

$pass = new String::Random;
my $array_counter=0;

my @regex_array = ();

push(@regex_array, $pass->randregex($regex_from_file));

#print "@regex_array";
$array_counter++;

while ($array_counter != $anzahl_regex)
{

    print $array_counter;
    my $tmpvar = $pass->randregex($regex_from_file);
    my $tmpcheck = 0;
    my $tmparraylength = scalar (@regex_array);

    for ($i=0; $i<= $tmparraylength ;$i++)
    {

        if ($tmpvar == $regex_array[$i]) # ERROR
        {
            $tmpcheck =1;
        }
    }



    if ($tmpcheck == 0) # es wurde kein duplikat gefunden
    {
        push(@regex_array,$tmpvar);
        $arraycounter++;
    }

    $arraycounter++;

}
like image 662
Tyzak Avatar asked Feb 23 '23 17:02

Tyzak


1 Answers

== is used to compare numbers. Use eq to compare strings:

if ($tmpvar eq $regex_array[$i]) 

Also, you're going beyond the end of regex_array in your for loop:

for ($i=0; $i < $tmparraylength ;$i++)
              ^ this must not be <=

Finally, you're doing way too much work. Use a hash, it automatically "removes duplicate keys".

my %temp_hash;
while (scalar(keys %temp_hash) < number_of_things_you_want) {
  $temp_hash{$pass->randregex($regex_from_file)}++;
}
@regex_array = keys %temp_hash;
like image 159
Mat Avatar answered Feb 27 '23 04:02

Mat