5% assure discount from here only

Tuesday, July 10, 2012

(30) How to read and print the content of file, using line number?

Solution:

Sometime we need to print or show content from file on basis of line number.

Suppose we have a file, which contains 1000 of lines and we need to print the content from line number 30 to 50.

Following example will show, how can we do this :-

open FILE, "/location/filename";
while(<FILE>){
if($. > 29 && $. < 51){ # Here $. represents the line number
print $_; # Here $_ represents the content
}
}
close FILE;

1 comment:

  1. # Use lexical filehandle and three-arg open
    # Check return value from open()
    open my $file, '<', '/location/file' or die $!;

    while (<$file>) {
    # flip-flip operator and statement modifier
    # Leads to more readable code
    # Oh, and print() uses $_ by default
    print if 30 .. 50;
    }

    # No need to explicitly close lexical filehandles.

    ReplyDelete