Hi Anonymous,

You're reading your entire file into memory, which isn't necessary because it looks like all you want is a sliding window over a certain number of lines from the file. This can be done by pushing each element onto the end of an array and then shifting elements off the beginning. This can even be done in a one-liner - see perl's -n and -l switches in perlrun:

$ perl -wnle 'push @x, $_; if(@x>=2) {print "@x"; shift @x}' input.txt Hello I I am am happy $ perl -wnle 'push @x, $_; if(@x>=3) {print "@x"; shift @x}' input.txt Hello I am I am happy

Another solution might be the core module Tie::File. Note I haven't tested this for efficiency, but since the module doesn't read the entire file into memory this solution should still be better than doing that. The module does have to scan the file once to get the number of records contained within:

#!/usr/bin/env perl use warnings; use strict; use Tie::File; use Fcntl 'O_RDONLY'; die "Usage: $0 INPUTFILE WINSIZE\n" unless @ARGV==2; my ($INPUTFILE,$WINSIZE) = @ARGV; tie my @array, 'Tie::File', $INPUTFILE, mode => O_RDONLY; $, = " "; $\ = "\n"; # output field/record separators for my $i (0..@array-$WINSIZE) { print @array[$i..$i+$WINSIZE-1]; }

Example usage:

$ perl window.pl input.txt 2 Hello I I am am happy

Update: My first solution is basically a one-liner version of Marshall and LanX's solutions, and my second solution is quite similar to BrowserUk's solution. Also switched from using print "@...\n" to setting $, and $\.

Hope this helps,
-- Hauke D


In reply to Re: Create n-grams from tokenized text file by haukex
in thread Create n-grams from tokenized text file 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.