Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

extract range from array of data

by theleftright (Novice)
on Dec 26, 2015 at 11:53 UTC ( #1151188=perlquestion: print w/replies, xml ) Need Help??

theleftright has asked for the wisdom of the Perl Monks concerning the following question:

Howdy everyone and merry perlmass! blah.txt contains the following data:
junk junk junk junk start not junk not junk end junk junk
more junk
open (hFile, "blah.txt"); @d = <hFile>; close hFile;
now how would i extract only:
start not junk not junk end
from that array? thanks all :) I have looked around, all i can find is how to do this on a string, but then i risk loosing all the nowlines. p.s: would be better if this was possible in 1 line

Replies are listed 'Best First'.
Re: extract range from array of data
by BrowserUk (Patriarch) on Dec 26, 2015 at 12:04 UTC

    Use the flip-flop operator:

    @d = grep{ /^start$/ .. /^end$/ } <hFile>;

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.

      BrowserUK you just blew my mind, thanks for the tip!

      thanks (y) perfect.
Re: extract range from array of data
by QuillMeantTen (Friar) on Dec 26, 2015 at 12:44 UTC

    First, loading it all inside an array might not be a good idea, if its a very large file you are asking for trouble, why not read it line by line until you reach start, save the lines until you read end and close the file at that time?

      There's a discussion of this approach in perlfaq6: "How can I pull out lines between two patterns that are themselves on different lines?" — even a one-liner! See also the discussion of the scalar context  .. flip-flop operator in Range Operators (scalar context sub-section) in perlop (some examples of what you want there also). (Update: See also Flipin good, or a total flop?, also with code that's almost exactly what theleftright seems to want.)

      Give a man a fish:  <%-{-{-{-<

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1151188]
Approved by BrowserUk
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (5)
As of 2022-06-27 10:48 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (88 votes). Check out past polls.