#!/usr/bin/perl use strict; use warnings; local $/ = "\nProduct:\n"; while ( ) { my @line = map { /Product:/ ? () : (split " ")[0] } split /\n/; print join ' + ', @line; print " = ", common( \@line ), "\n"; } sub common { my $line = shift; my $short = 65536; for ( @$line ) { $short = length $_ if length $_ < $short }; my $index; for ( --$index ; $short-- ; --$index ) { my $str = substr($line->[0], $index); for ( @$line ) { return substr($_, ++$index) if substr($_, $index) ne $str; } } } __DATA__ Product: redball This is for Mike. greenball This is for Dave. Product: smallbox This is for apples bigbox This is for orange