in reply to Skipping the first 4 lines of a file:: Is there a better way?

If the size of the file is not a concern:
... my $skip = 4; { open FH, "filename"; local@_ = <FH>; close FH; @_ = split /(?:.+\n){$skip}/m, "@_"; for( @_ ){ # work without first four lines } } ...


Replies are listed 'Best First'.
Re^2: Skipping the first 4 lines of a file:: Is there a better way?
by Fletch (Bishop) on Jun 03, 2005 at 14:22 UTC
    @_ = split /(?:.+\n){$skip}/m, "@_";

    Gah, that's terribly inefficient. splice( @_, 0, $skip ) at the least if you feel you have to modify @_. foreach( @_[  $skip .. $#_ ] ) { ... } would be even better since it doesn't have to move anything around.

    Update: Changed from hardcoded 4 to $skip to match.

    --
    We're looking for people in ATL

    A reply falls below the community's threshold of quality. You may see it by logging in.
Re^2: Skipping the first 4 lines of a file:: Is there a better way?
by fishbot_v2 (Chaplain) on Jun 03, 2005 at 15:02 UTC

    Efficiency aside, does this really work? Okay, well, I know the answer: it doesn't. There is no limit on the split, and the delimiter is any {4} lines.

    So, if my file is 10 lines long, I get two empty strings, then the remaining 2 lines. Infact, you only ever end up with the last X lines of your file (where X = lines % $skip), preceeded with (lines div $skip) empty strings.

    @_ = split /(?:.+\n){$skip}/m, "@_", 2; # add limit # closer, but now I have @_ == 2, # since there is a leading null shift @_; # now I have a single element array with # the file remainder in $_[0] @_ = split /\n/, $_[0]; # now I have the desired results.

    I agree that solutions don't always need to be the most efficient, but parsing through the entire file at least three times is O(n) where O(1) is available in a single line of code.