पूरी File पढ़ना
List context में <$fh> हर line return करता है, और एक special variable set करना file को एक piece में पढ़ सकता है।
In this page:
पूरी 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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- बहुत बड़ी files को memory में slurp करना
- $/ को undef set करना और इसे restore करना भूल जाना
- यह भूल जाना कि 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: