#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    15
    Rep Power
    0

    Comparing two rows ia a array


    Hi to all,
    my file contains two rows and 8 coulmns, i want to compare these two rows across all the 8 coulmns and if they match EQ ( for example for column A 1st row value is equal to 2nd row vlaue) else NEQ. I succeed to read my file into array and now i can print my each individual coulmns using array index but i do not know how to compare them here is the code i used till now

    Code:
    #!/usr/bin/perl
    $filename = 'maize.csv';
    open(FILE, $filename) or die "Could not read from $filename, program halting.";
    while(<FILE>)
    {
      chomp;
      @fields = split(',', $_);
     print "$fields[11]\n";
    }
    close FILE;
    please help me how to match one with another row.
    Thanking you very much,
    Regards,
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    830
    Rep Power
    496
    If you have only two rows, store the fields of the first row into an array and those of the second line into another array. Then compare the fields of the two array one by one. For example something like this (quick untested code):

    Perl Code:
    my  @array1 = split /,/ <FILE>;
    my @array2 = split /,/, <FILE>;
    foreach my $i (0..7) {
         if ($array1[$i] eq $array2[$i]) {
              # do something;
         } else {
              # do something else;
         }
    }


    Please note that it is better to use lexical filehandlers and the 3-argument syntax for opening a file:

    Perl Code:
    open my $FILE, "<", $filename or die "Could notopen $filename $! \n";
  4. #3
  5. !~ /m$/
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    May 2004
    Location
    Reno, NV
    Posts
    4,254
    Rep Power
    1810
    Also, if you are using a sufficiently modern version of perl, you can use the smart match operator.

    From perlfaq4

    How do I test whether two arrays or hashes are equal?
    With Perl 5.10 and later, the smart match operator can give you the answer with the least amount of work:

    Code:
    use 5.010;
    
    if( @array1 ~~ @array2 ) {
       say "The arrays are the same";
    }
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    830
    Rep Power
    496
    I also thought of the smart match operator. But if you want to compare the whole thing in one swoop, then there is not point splitting the records, you might as well compare the data lines (string comparison).

IMN logo majestic logo threadwatch logo seochat tools logo