← Back to Perl Course | Chapter 5: File I/O | Lesson 3 of 7

Files को Line by Line पढ़ना

diamond operator एक बार में एक line पढ़ता है, इसलिए huge files भी कम memory इस्तेमाल करती हैं।

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

perl
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
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. chomp भूल जाना और doubled newlines पाना
  2. एक huge file के लिए पूरी file को एक array में पढ़ना
  3. यह भूल जाना कि 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.