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;
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;
# Use lexical filehandle and three-arg open
ReplyDelete# 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.