Files को Line by Line पढ़ना
diamond operator एक बार में एक line पढ़ता है, इसलिए huge files भी कम memory इस्तेमाल करती हैं।
In this page:
Files Line by Line पढ़ना
Scalar context में <$fh> अगली line return करता है, इसकी newline समेत, और file के अंत पर undef return करता है। while (my $line = <$fh>) जैसा एक while loop हर line पढ़ता है, और Perl एक implicit defined test add करता है ताकि सिर्फ "0" वाली एक line loop न रोके। Special variable $. current line number hold करता है, और chomp trailing newline remove करता है।
Note:
एक while loop से पढ़ना memory कम रखता है, इसलिए बड़ी files के लिए इसे prefer करें।
उदाहरण: Reading files line by line
use strict;
use warnings;
my $file = "demo_lines.txt";
open(my $w, '>', $file) or die "Cannot write: $!";
print $w "alpha\nbeta\n\ngamma\n";
close $w;
open(my $fh, '<', $file) or die "Cannot read: $!";
while (my $line = <$fh>) {
chomp $line;
next if $line eq '';
print "$.: $line\n";
}
close $fh;
unlink $file;
# Output:
# 1: alpha
# 2: beta
# 4: gamma
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- chomp भूल जाना और doubled newlines पाना
- एक huge file के लिए पूरी file को एक array में पढ़ना
- यह भूल जाना कि last line में शायद newline न हो
चैप्टर सारांश
- एक while loop में <$fh> line by line पढ़ता है
- chomp newline remove करता है
- $. line number hold करता है
- File के अंत पर loop खत्म होता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: