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

पूरी File पढ़ना

List context में <$fh> हर line return करता है, और एक special variable set करना file को एक piece में पढ़ सकता है।

पूरी File पढ़ना

List context में readline operator बाकी सारी lines को एक list की तरह return करता है, जो छोटी files के लिए handy है। पूरी file को एक single string की तरह पाने के लिए, एक local block के अंदर input record separator $/ को undef set करें, जिसे slurping कहते हैं। एक list के साथ chomp हर element से newline remove करता है।

Note: एक छोटे block के अंदर local $/; इस्तेमाल करें ताकि बदलाव program के बाकी हिस्से को प्रभावित न करे।

उदाहरण: Reading a whole file

perl
use strict;
use warnings;

my $file = "demo_slurp.txt";
open(my $w, '>', $file) or die "Cannot write: $!";
print $w "one\ntwo\nthree\n";
close $w;

open(my $fh, '<', $file) or die "Cannot read: $!";
my @lines = <$fh>;
close $fh;
chomp @lines;
print "lines: ", scalar(@lines), " -> @lines\n";

my $content = do {
    local $/;
    open(my $in, '<', $file) or die "Cannot read: $!";
    <$in>;
};
print "characters: ", length($content), "\n";
my $newlines = () = $content =~ /\n/g;
print "newlines: $newlines\n";
unlink $file;

# Output:
# lines: 3 -> one two three
# characters: 14
# newlines: 3
{# 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. बहुत बड़ी files को memory में slurp करना
  2. $/ को undef set करना और इसे restore करना भूल जाना
  3. यह भूल जाना कि list context में पढ़ा हर element फिर भी एक newline से खत्म होता है
चैप्टर सारांश
  • List context सारी lines return करता है
  • local $/ = undef एक file slurp करता है
  • chomp एक पूरे array पर काम करता है
  • सिर्फ छोटी files slurp करें
🔒

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.