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

Files Open और Close करना

open एक filehandle को एक file से connect करता है, और close इसे disconnect करता है।

Files Open और Close करना

तीन-argument open एक filehandle, एक mode, और एक file name लेता है; modes हैं पढ़ने के लिए <, लिखने के लिए > (जो file truncate करता है), append के लिए >>, और पढ़ने और लिखने दोनों के लिए +<। failure पर open false return करता है और $! में reason store करता है, इसलिए इसके बाद आमतौर पर or die आता है। my से declared एक lexical filehandle इस्तेमाल करना modern style है, और यह scope से बाहर जाने पर automatically close हो जाता है।

Note: हमेशा open का result check करें; एक missing file एक normal situation है, impossible नहीं।

उदाहरण: Opening and closing files

perl
use strict;
use warnings;

my $file = "demo_open.txt";
open(my $out, '>', $file) or die "Cannot open $file: $!";
print $out "created by Perl\n";
close($out) or die "Cannot close $file: $!";

open(my $in, '<', $file) or die "Cannot open $file: $!";
my $line = <$in>;
close($in);
print "read back: $line";

if (open(my $missing, '<', "no_such_file.txt")) {
    print "unexpectedly opened\n";
} else {
    print "open failed: $!\n";
}
unlink $file;

# Output:
# read back: created by Perl
# open failed: No such file or directory
{# 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. यह check न करना कि open succeed हुआ
  2. जब आपका मतलब >> था तब > इस्तेमाल करना और file erase करना
  3. एक variable file name के साथ open के old two-argument form इस्तेमाल करना
चैप्टर सारांश
  • open(my $fh, MODE, FILE) एक file खोलता है
  • < पढ़ता है, > लिखता है, >> append करता है
  • or die और $! से failures check करें
  • close handle release करता है
🔒

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.