문제

I have a sub, and it is not returning anything despite of a return statement:

 $match = findInArray($$firstArray[$i], $secondArray);

 sub findInArray() {
     my $findThis = $_[0];
     my $findIN = $_[1];
     for (my $i = 0;$i <= $#$findIN;$i++) {
         if (index($findThis, $$findIN[$i]) != -1) {
             $i = 100000;
             return $$findIN[$i];
         }
     }
     return '';
 }

The debug window shows nothing for var $match:

   DB<86>
   main::findInArray(ConfCompare:60):                            return $$findIN[$i];
     DB<86> p $$findIN[Si]
   platform/ss7statistics;enableDetailedLinkData;true
     DB<87> n
   main::findDifferencesSclarArrays(ConfCompare:40):
   40:                     if ($match eq ''){
     DB<87> p $match

     DB<88>
도움이 되었습니까?

해결책

I'm guessing the problem is the fact that you're setting $i to 100000 for some reason before returning $$findIN[$i]. It's quitely likely that @$findIN doesn't have 100001 elements, so $$findIN[$i] will try to fetch an element that doesn't exist, resulting in the function returning undef.

다른 팁

Your use of index is backwards. The first argument is the string to search within, and the second argument is the thing that you're looking for.

Assuming that your match works, by assigning an impossibly high value to $i will cause return $$findIN[$i] to return undefined (undef).

You may also want to consider rewriting your function to be a bit more clear:

sub findInArray {
    my ($findThis, $array) = @_;
    foreach my $element ( @$array ) {
        return $element if index($element, $findThis) != -1;
    }
    return '';
}

This maintains exactly what your current subroutine is doing. If you don't mind looking through the whole array, you can also do this:

sub findInArray {
    my ($findThis, $array) = @_;
    my ($match) = grep { index($element, $findThis) != -1 } @$array;
    return $match // '';
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top