Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - the fastest way to read a range of lines from a file into a variable

Tags:

perl

Given a start and end line number, what's the fastest way to read a range of lines from a file into a variable?

like image 502
powerboy Avatar asked Jan 25 '26 21:01

powerboy


2 Answers

Use the range operator .. (also known as the flip-flop operator), which offers the following syntactic sugar:

If either operand of scalar .. is a constant expression, that operand is considered true if it is equal (==) to the current input line number (the $. variable).

If you plan to do this for multiple files via <>, be sure to close the implicit ARGV filehandle as described in the perlfunc documentation for the eof operator. (This resets the line count in $..)

The program below collects in the variable $lines lines 3 through 5 of all files named on the command line and prints them at the end.

#! /usr/bin/perl

use warnings;
use strict;

my $lines;
while (<>) {
  $lines .= $_ if 3 .. 5;
}
continue {
  close ARGV if eof;
}

print $lines;

Sample run:

$ ./prog.pl prog.pl prog.c main.hs
use warnings;
use strict;


int main(void)
{
import Data.Function (on)
import Data.List (sortBy)
--import Data.Ord (comparing)
like image 178
Greg Bacon Avatar answered Jan 27 '26 11:01

Greg Bacon


You can use flip-flop operators

while(<>) {
if (($. == 3) .. ($. == 7)) {
    push @result, $_;
}
like image 43
Oleksandr Tymoshenko Avatar answered Jan 27 '26 10:01

Oleksandr Tymoshenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!