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

Question:Some file contains something like this define#1 junk define#43... ...... What I want to know: How can I just grab the lines I want.File contains 345 lines but I want 32 lines only...Any ideas? thankx

Replies are listed 'Best First'.
Re: Writing files
by lhoward (Vicar) on Jul 28, 2000 at 21:46 UTC
    How do you know which lines you want? It is because of the line's contents? Or because of the lines position (i.e. line number)?

    If you are trying to find a line by line-number and and you have fixed-length lines (all lines are the same length). Then you could seek to move to the correct location in the file and then read in the data. If the lines are not fixed-length then you will have to examine every line, counting line numbers and just not processing the ones you don't care about.

    If you are trying to extract lines based on their contents, then you will have to examine each line in the file. In order to determine if you are interested in it.

      I think it would be better if I examine all the lines and get the one I wanted. But they are all differeent. But how? Thankx
        two words: regular expressions.
        two more words: not necessarily.
        open FILE, "file.txt" or die "can't do : $!\n"; while (<FILE>) { # do some test on $_ # if it's a string you want, keep it } close FILE;
        those tests are most likely going to be some sort of regular expression. but it depends on what you are looking for. what lines do you want to keep? how do you know you want to keep them?
Re: Writing files
by KM (Priest) on Jul 28, 2000 at 21:24 UTC
    You could use seek() or something like that. Is it the first 32 lines you want? If so you could do:
    open FH, $file or die "couldn't open: $!"; @first_32 = map scalar(<FH>), 1..32;

    But, the real solution is where are the 32 lines? Are they contiguous? Are the lines always know (like line 10, 13, 33, 45, etc...), or are the 32 lines varied?

    Cheers,
    KM

      They are not first 32 lines.But I know the lines. They could be for example line32, 34, 56, 57, 89...etc. Thankx.
        Well, your file isn't too large. You could always do something like the following (sort of ugly):

        open(FH, .....) or die ....; my @lines = <FH>; close FH; my @wanted = @lines[31, 33, 55, 56, 88]; # remember 0 based.

        Cheers,
        KM