tags:

views:

155

answers:

1

I have 10 arrays, each consisting of similar type of values. I want to capture subset of these values (capture only the digits) from each array and then compare it with subset from other array. And also, I want to capture the number part of values from both arrays only when there is no dash in the value (i.e. 2EF = capture '2'but if 45F- then not capture anything, move to next value).

_ DATA _

@array1 = (-, 1EF, 2DG, 3GF, 4F-, -, ....99GY);

@array2 = (-, 1EF, 2DF, 3SD, 4DE, -, ....99HK);

Any two arrays out of 10 can be compared at a time. So , I have stored them in an array '@allarrays' and loop it to compare. In the following script, I am able to capture the digit of first array perfectly but I am unable to compare digits from second array. The value of $digit1 (corresponding to @array1) gets copied into $digit2 (corresponding to @array2). Any suggestions on whats going wrong?

sub compareArrays {
    my @array = @_; #passes an array @allarray which has @array1, @array2 ...@array10
        for (my $p=0; $p<10; $p++){ # since total number of arrays is 10
            for (my $r=$p+1; $r<10; $r++){ #to compare arrays
         for (my $q=0; $q<$colsInArray; $q++){
             my $string1= $array[$p][$q];
             my $string2= $array[$r][$q];

             #array1
              $string1=~ /(\d+)[A-Z]+/;
          my $digit1 = $1; #capture digit part of array value
          print "array1: $digit1\n"; #works fine, prints captured $digit1                          
             #array2
          $string2=~ /(\d+)[A-Z]+/;
          my $digit2 = $1;
          print "array2: $digit2\n"; #does not capture the value in $digit2, instead copies $digit1

             if ($digit1 == $digit2){ 
          print "$digit1 : $digit2\n"; 
             }        
         }

            }
        }
}

_ UPDATE _ calling compareArrays as:

&compareArrays(@allarrays);
+1  A: 

When I use your test code, it does capture the value in $digit2. You might show us how you are calling compareArrays.

You should check if the regex matched before accessing $1; if the regex failed, $1 will be left over from the previous match. You don't have anything to skip values containing -. Assuming the digits are always at the beginning, followed by only uppercase letters, you could combine both those by saying

my ($digit1) = $string1 =~ /^([0-9]+)[A-Z]+\z/ or next;
ysth
@ysth: I commented everything for $digit1 to see if regex for $digit2 works. On printing $digit2, it is clear that the regex is working. But, when I combine then $digit2 has the same value as $digit1. I have also updated on how I am calling compareArrays.
shubster
@ysth: I replaced $string1=~ /(\d+)[A-Z]+/; my $digit1 = $1; with what you wrote above. Replacing it with your expression seems to solve the purpose. But, I am not sure why? Anyway, thanks! :)
shubster