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

Files में Writing

एक filehandle के साथ print एक file में text लिखता है।

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

perl
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
{# 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. filehandle के बाद एक comma add करना
  2. newline भूल जाना ताकि सारी lines साथ चल जाएँ
  3. एक 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:

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.