I may have misunderstood but I think you want each pair overlapping, i.e "this word and that" has three pairs viz. "this word", "word and" and "and that". If that is the case you can do a a global regex match using a capture for one word followed by non-word characters then a look-ahead assertion for the next word, also with a capture.

use strict; use warnings; open my $inFH, q{<}, \ <<'END_OF_FILE' or die qq{open: $!\n}; peter piper picked a peck of pickled peppers a peck of pickled peppers peter piper picked if peter piper picked a peck of pickled peppers where's the peck of pickled peppers peter piper picked END_OF_FILE my $textFile = do { local $/; <$inFH>; }; close $inFH or die qq{close: $!\n}; my $rxWordPair = qr {(?x) ([\w'-]+) \W+ (?=([\w'-]+)) }; my %pairFrequencies; while ( $textFile =~ m{$rxWordPair}g ) { $pairFrequencies{ qq{$1 $2} } ++; } print map { qq{$_: $pairFrequencies{ $_ }\n} } sort { $pairFrequencies{$b} <=> $pairFrequencies{$a} || $a cmp $b } keys %pairFrequencies;

This produces

of pickled: 4 peck of: 4 peter piper: 4 pickled peppers: 4 piper picked: 4 a peck: 3 peppers peter: 2 picked a: 2 if peter: 1 peppers a: 1 peppers where's: 1 picked if: 1 the peck: 1 where's the: 1

I hope this is useful.

Cheers,

JohnGG


In reply to Re: Dividing a file into groups of two words and counting them by johngg
in thread Dividing a file into groups of two words and counting them by Anonymous Monk

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.