#!/usr/bin/perl use strict; use Algorithm::Diff qw/traverse_sequences/; my @strings = <>; chomp @strings; my ( $longestMatch, $currentMatch ); my ( @seq1, @seq2 ); for my $i ( 0 .. $#strings-1 ) { @seq1 = split //, $strings[$i]; for my $j ( $i+1 .. $#strings ) { @seq2 = split //, $strings[$j]; $longestMatch = $currentMatch = ""; traverse_sequences( \@seq1, \@seq2, { MATCH => \&add2match, DISCARD_A => \&end_match, DISCARD_B => \&end_match } ); ### update: add a direct call to "end_match()" here, ### in case traverse was still matching at end-of-string: end_match( 'EOS' ); print "LCS for $i :: $j = |$longestMatch|\n"; } } sub add2match { my ( $ptrA, $ptrB ) = @_; $currentMatch .= $seq1[$ptrA]; # warn "match at i=$ptrA, j=$ptrB : =$seq1[$ptrA]= ; cm=$currentMatch=\n"; } sub end_match { $longestMatch = $currentMatch if ( length( $longestMatch ) < length( $currentMatch )); $currentMatch = ""; # warn "match ended at @_ : lm=$longestMatch=\n"; }