in reply to how to read a particular paragraph from middle of a file line by line and enter each string in the line as an element of an array

Assuming the end of a paragraph is indicated by an empty line or --in other words-- "\n\n", you can set the special variable $/ to "\n\n" and then each iteration of <filehandle> will read a whole paragraph. Stop reading when you have reached the target paragraph

Next you split that paragraph on "\n" to get each line and the you split each line on \s (whitespace) to get each word.

use Modern::Perl; use Data::Dump qw/dump/; my $paragraph; { local $/ = "\n\n"; $paragraph = <DATA> for 1 .. 3; # we need the third paragraph } my @words; push @words, map {[split /\s/]} split /\n/, $paragraph; say dump(@words); __DATA__ This is the start of the first paragraph. This is the second line of this first paragraph. And this is the last line of it. Here starts the second paragraph. This is the second line of this second paragraph. And this is the last line of it. Here starts the third paragraph. This is the second line of this third paragraph. And this is the last line of it. Here starts the fourth paragraph. This is the second line of this fourth paragraph. And this is the last line of it.
Output:
( ["Here", "starts", "the", "third", "paragraph."], [ "This", "is", "the", "second", "line", "of", "this", "third", "paragraph.", ], ["And", "this", "is", "the", "last", "line", "of", "it."], )
Update: added an example program.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

  • Comment on Re: how to read a particular paragraph from middle of a file line by line and enter each string in the line as an element of an array
  • Select or Download Code