Scotmonk has asked for the wisdom of the Perl Monks concerning the following question:

I have to search through data and find instances that match and those that do not match, line on line

I have this input data

1 2 3 4
1 2 3 5
1 2 4 6
1 2 3 4
1 2 3 5
1 2 4 7
4 6 3 9

I need help with code that will read the first five lines of this data, and compare all values found with those values in line 6. So that the output (to output.txt) is;

match:
1 2 4
no match:
7
- then for the code to move on and do the same for lines 2-6 with line 7, so the output file would read
match:
1 2 4
3 4 6

no match:
7
9

and so on down through my data.

could you help me please with code that will read the data, compare it as above and write the data to an output.txt file

thankyou

Replies are listed 'Best First'.
Re: comparing lines of data
by tybalt89 (Monsignor) on Nov 15, 2019 at 20:31 UTC
    #!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11108762 use warnings; $_ = <<''; 1 2 3 4 1 2 3 5 1 2 4 6 1 2 3 4 1 2 3 5 1 2 4 7 4 6 3 9 my (@match, @nomatch); while( /^(?=((?:.*\n){5})(.*\n))/gm ) { my ($five, @six) = ($1, sort split ' ', $2); my %found = map +($_ => 1), split ' ', $five; push @match, "@{[ grep $found{$_}, @six ]}\n"; push @nomatch, "@{[ grep !$found{$_}, @six ]}\n"; } print "match:\n", @match, "\nnomatch:\n", @nomatch;

      Thankyou tybalt89

      Could I ask another ?

      Could you adjust that code so that it will read the input data from a file called input.txt

      and print the match data to match.txt and no match.txt ?

      Or should I ask as a new question ?

      Thanks again :)

        Could I ask another ?

        No! (Just kidding :)

        ... adjust that code so that it will read the input data from a file ... and print the match data to [files] ...

        Please see also perlintro, open, perlopentut, and some of the articles in Input and Output, such as File Input and Output (but use the modern "three argument" call to open; the latter article is old and often uses "global" filehandles in its examples).


        Give a man a fish:  <%-{-{-{-<

        To read from a file, all you have to do is :

        my $Filename = “...”; my $Filehandle; open $Filehandle, ‘<‘, $Filename or die “cant open file.\n”; my @Lines = <$Filehandle>; close $Filehandle; ...