File Tests करना
-e और -d जैसे short operators इस्तेमाल करने से पहले एक file के बारे में सवाल पूछते हैं।
In this page:
File Tests
File test operators बिना खोले एक path check करते हैं: -e test करता है कि यह exist करती है, -f कि यह एक plain file है, -d कि यह एक directory है, -s इसका size return करता है (या empty होने पर false), और -r, -w, और -x permissions test करते हैं। ये true या false return करते हैं, इसलिए ये एक if statement में naturally fit होते हैं। दो related functions, rename और unlink, files move और delete करते हैं।
Note:
-s जैसा एक test bytes में size return करता है, जो एक empty file के लिए false है।
उदाहरण: File tests
use strict;
use warnings;
my $file = "demo_tests.txt";
open(my $fh, '>', $file) or die "Cannot write: $!";
print $fh "12345\n";
close $fh;
print "exists: ", (-e $file ? "yes" : "no"), "\n";
print "plain file: ", (-f $file ? "yes" : "no"), "\n";
print "directory: ", (-d $file ? "yes" : "no"), "\n";
print "size: ", -s $file, "\n";
print "readable: ", (-r $file ? "yes" : "no"), "\n";
rename $file, "demo_renamed.txt" or die "Cannot rename: $!";
print "old name exists: ", (-e $file ? "yes" : "no"), "\n";
print "new name exists: ", (-e "demo_renamed.txt" ? "yes" : "no"), "\n";
unlink "demo_renamed.txt";
print "after unlink: ", (-e "demo_renamed.txt" ? "exists" : "gone"), "\n";
# Output:
# exists: yes
# plain file: yes
# directory: no
# size: 6
# readable: yes
# old name exists: no
# new name exists: yes
# after unlink: gone
Login to try C/C++/Java/PHP code in the editor
आम गलतियां
- -e (exists) को -f (plain file) से confuse करना
- यह मान लेना कि -s एक empty file के लिए true return करता है
- एक file check करना और फिर इसे खोलना, यह भूल जाना कि यह बीच में बदल सकती है
चैप्टर सारांश
- -e exists, -f plain file, -d directory check करते हैं
- -s size return करता है
- -r -w -x permissions check करते हैं
- rename और unlink move और delete करते हैं
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: