comparing the rows in an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Gosik
    New Member
    • Jan 2013
    • 1

    comparing the rows in an array

    Hello!

    I have two arrays:
    date1:
    13:26:10
    13:26:11
    13:26:12
    13:26:13
    13:26:14

    date2:
    13:26:07.1
    13:26:08.1
    13:26:09.1
    13:26:10.1
    13:26:11.1
    13:26:12.1
    13:26:13.1

    I would like to compare rows in array date1 and date2, and the rows that have the same time, I want to see.

    I have written the code:
    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my @date1;
    my @date2;
    open (K, 'plik1.txt'); while (<K>) {
    open (P, 'plik2.txt'); while (<P>) {
    
    chomp(@date1 = <K>);
    chomp(@date2 = <P>);
    
     }
    }
    
    close(K);
    close(P);
    
    my @pasuje;
    my @pas;
    
    
    #my @pasuje;
    
      foreach (@date1) {
      push @pasuje, grep(/^$_/, @date2);
      print "$_ \n";
      }
      print @pasuje;
    However, all the items are displayed in the array date2.
    I have the feeling that nothing is inserted into the $ _.
    Can someone indicate the error in my code?

    I will be very grateful for your help.
    Last edited by Rabbit; Jan 21 '13, 10:01 PM. Reason: Fixed code tags.
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    Ok, I was able to get this working for you, but had to do some major rework on your code. First, up where you opened the filehandles for each file, you opened one as a sub inside the other. You have to be careful of how you are attempting to do things. It is easier to just open the file handles and then set the arrays equal to the filehandles, which will simply create an array out of the data in the file handles.

    I many have gone a bit farther in the comparison (as I am sure some people can come up with shortcuts for what I did), but I did a pair of nested for loops for the comparison.

    Hopefully this helps you.

    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
     
    my @date1;
    my @date2;
    open (K, 'plik1.txt'); while (<K>) {
    open (P, 'plik2.txt'); while (<P>) {
     
    chomp(@date1 = <K>);
    chomp(@date2 = <P>);
     
     }
    }
     
    close(K);
    close(P);
     
    my @pasuje;
    my @pas;
     
     
    #my @pasuje;
     
      foreach (@date1) {
      push @pasuje, grep(/^$_/, @date2);
      print "$_ \n";
      }
      print @pasuje;
    Regards,

    Jeff

    Comment

    Working...