Files Open और Close करना
open एक filehandle को एक file से connect करता है, और close इसे disconnect करता है।
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- यह check न करना कि open succeed हुआ
- जब आपका मतलब >> था तब > इस्तेमाल करना और file erase करना
- एक 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: