Files में Writing
एक filehandle के साथ print एक file में text लिखता है।
In this page:
Files में लिखना
filehandle को print, printf, या say के ठीक बाद रखें, इसके बाद कोई comma नहीं। > से open करना file बनाता है या एक existing को खाली करता है, जबकि >> अंत में add करता है। आप एक पूरी list भी print कर सकते हैं, और printf formatted lines देता है।
Note:
जब filehandle एक complex expression में stored हो, जैसे एक hash element, print {$fh} ... जैसा एक block इस्तेमाल करें।
उदाहरण: Writing to files
use strict;
use warnings;
my $file = "demo_write.txt";
open(my $fh, '>', $file) or die "Cannot write $file: $!";
print $fh "first line\n";
printf $fh "%-6s %3d\n", "apples", 12;
my @more = ("second\n", "third\n");
print $fh @more;
close $fh;
open($fh, '>>', $file) or die "Cannot append $file: $!";
print $fh "appended line\n";
close $fh;
print "file size: ", -s $file, " bytes\n";
open($fh, '<', $file) or die;
print while <$fh>;
close $fh;
unlink $file;
# Output:
# file size: 49 bytes
# first line
# apples 12
# second
# third
# appended line
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- filehandle के बाद एक comma add करना
- newline भूल जाना ताकि सारी lines साथ चल जाएँ
- एक handle से पढ़ना जो सिर्फ लिखने के लिए open हुआ था
चैप्टर सारांश
- print $fh LIST एक file में लिखता है
- filehandle के बाद कोई comma नहीं
- > truncate करता है और >> append करता है
- printf filehandles के साथ भी काम करता है
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: