#!/usr/bin/perl use strict; use warnings; sub lcs_arrays { my ( $a1, $a2 ) = @_; my @matches = (); my $longest = 0; for my $b1 ( 0 .. $#$a1 ) { for my $b2 ( 0 .. $#$a2 ) { if ( $$a1[$b1] eq $$a2[$b2] ) { my @match = ( $$a1[$b1] ); my $e1 = $b1+1; my $e2 = $b2+1; while ( $e1 < @$a1 and $e2 < @$a2 ) { last if ( $$a1[$e1] ne $$a2[$e2] ); push @match, $$a1[$e1]; $e1++; $e2++; } if ( @match > $longest ) { push @matches, \@match; $longest = @match; } } } } return $matches[$#matches]; # array ref -> longest matching list } my @t = ( "now is the time for all good men to come to the aid of", "now is the winter of our discontent made glorious", "the time for all good parties now is the winter", "we expect good men to come to the aid of good parties", "I KNOW THIS SENTENCE WILL NOT MATCH", ); if ( @ARGV > 1 and -f $ARGV[0] ) { local $/; @t = (); for my $f ( @ARGV ) { open( I, $f ); push @t, <>; close I; } } for my $i ( 0 .. $#t-1 ) { for my $j ( $i+1 .. $#t ) { my @a = split " ", $t[$i]; my @b = split " ", $t[$j]; my $r = lcs_arrays( \@a, \@b ); if ( defined $r ) { print "$i-$j: @$r\n"; } else { print "$i=$j: NO_MATCHES\n"; } } } #### list1: one two three five six seven list2: two three five eight five six seven