#!/share/bin/perl -w # This is the example for the "key word in context" listing. # It reads a file of text records, e.g. of film titles, one record per line # Each Capitalized word on a line is a keyword # The program is to produce a key word in context listing with # the keywords lining up around column 50 of the output page # The output lines are composed, the keyword starts at column 50 # This special sort helper function compares substrings starting at this point sub by_keystr { my $str1 = substr($a,50); my $str2 = substr($b,50); if($str1 lt $str2) { return -1; } elsif($str1 eq $str2) { return 0; } else { return 1; } } # main program starts here @collection = (); while($title = ) { chomp($title); # split line into words at space characters @Title = split / / , $title; $start = ""; foreach $i (0 .. $#Title) { $Word = $Title[$i]; # Simple pattern test, does word start with a capital letter if($Word =~ /^[A-Z]/) { $end = ""; # There are neater ways of building this list! for($j=$i;$j<=$#Title;$j++) { $end .= $Title[$j] . " "; } # Use formatted print routine $line = sprintf "%50s %-50s\n", $start, $end; push(@collection, $line); } $start .= $Word . " "; } } @sortcollection = sort by_keystr @collection; foreach $entry (@sortcollection) { print $entry; }