开发者

Compare two regex with an If-Statement fails

开发者 https://www.devze.com 2023-04-12 23:23 出处:网络
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 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++;

}


== 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;


Don't use the numerical comparísson == use the string comparisson eq.

See here the Documentation on perldoc.perl.org


If all you want to do is de-dupe the array, this might be more suitable:

{
    my %h;
    map { $h{$_} = 1 } @all_regex;
    @all_regex = keys %h;
}

Be advised that it does not preserve the order of the original array.

0

精彩评论

暂无评论...
验证码 换一张
取 消