ZebraSocks
ZebraSocks

Reputation: 85

Perl: How do I read a text file word by word starting at a particular pattern?

I'm trying to write a script that reads a space-delimited text file and recognizes a certain pattern PATTERN. After recognizing PATTERN, the script should read RANDOM_NUMBER of words starting at PATTERN. For example, suppose PATTERN is a and RANDOM_NUMBER is 7. Then for this text file:

1 2 3 4 5 6
a b c d e f 
g h i j k j

I would want to get:

a b c d e f
g

as output.

So far, I've gotten to the point of recognizing these patterns, but I don't know how to handle it afterwards. What is the best way to read in the words?

By the way, I've looked at Read text file in Perl word by word instead of line by line and it's a little too vague for my purposes. Also, the answers do not provide much explanation in terms of what the code is doing.

Upvotes: 2

Views: 501

Answers (1)

Sobrique
Sobrique

Reputation: 53488

OK, so the trick here is to set $/ - the record separator. If we set it to ' ' we can iterate one 'word' at a time.

Then we can use the range operator to 'detect' if we are between our patterns.

local $/ = ' ';

while ( <DATA> ) {
    if ( m/a/ ..  10 ) { print; }
}

Now, this prints from a to "field 10" - which isn't particularly helpful, because that "count" starts at the start of the file. (By

So instead we probably want to 'trigger' when the seen condition is true, and continue for a number of other iterations:

#!/usr/bin/perl
use strict;
use warnings;

local $/ = ' ';

while (<DATA>) {
    if (m/a/) {
        print;
        for ( 2 .. 7 ) { print scalar <DATA>; } #2 because we already have "1"
        last; #assuming we only want to do this once. 
    }
}


__DATA__
1 2 3 4 5 6 
a b c d e f 
g h i j k j

Which prints:

a b c d e f 
g 

Upvotes: 6

Related Questions