#!/usr/bin/perl
# Key Word In Context in perl.
# See http://www.acm.org/classics/may96/ for the original problem statement.

sub kwic_cmp {
    if ($a =~ /^\s*\d+ (.*)/) {
	my $a_words = $1;
	if ($b =~ /^\s*\d+ (.*)/) {
	    my $b_words = $1;
	    return $a_words cmp $b_words;
	}
    }
}

while (<>) {
    my $lineno = sprintf "%5d", $.;
    chomp;
    @words = split /\s+/;
    for $i (0..$#words) {
	push @lines, join (' ', $lineno, @words[$i..$#words, 0..$i-1])."\n";
    }
}
    print sort kwic_cmp @lines;
