Updated to use less memory, and make it easier to do some Markov chain analysis should you so desire. Tweaked regex for some corner cases.

You may just want to build your index and get it over with. Note: this will use, as a wild guess, at least 3 times as much memory as the file size, so be careful with large files.

use warnings; use strict; my %index; while ( my $line = <DATA> ) { $line = lc $line; $line =~ s/^\P{Alnum}+|\P{Alnum}+$//g; my @words = split /\P{Alnum}*\s\P{Alnum}*/, $line; for ( 0 .. $#words ) { my $word = $words[$_]; $index{$word}{count}++; my ( $pre, $post ) = ( '', '' ); if ( $_ > 0 ) { $pre = $words[ $_ - 1 ]; } if ( $_ < $#words ) { $post = $words[ $_ + 1 ]; } push @{ $index{$word}{lines} }, [ $., $pre, $post ]; } } for my $word ( sort keys %index ) { print "$word - $index{$word}{count} time" . ( $index{$word}{count} == 1 ? '' : 's' ) . ":\n"; printf " Line %4d - %s $word %s\n", @$_ for ( @{ $index{$word}{ +lines} } ); print "\n"; } __DATA__ Mary had a little lamb, A little pork, a little jam, A little fish, some kangaroo, A pudding and some cookies too, An ice cream soda topped with fizz, And boy how sick our Mary is. Mary had a little lamb, Her daddy shot it dead. And now it goes to school with her, Between two hunks of bread.

In reply to Re: Finding word either side of a word match by thundergnat
in thread Finding word either side of a word match by Quicksilver

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.