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

File Tests करना

-e और -d जैसे short operators इस्तेमाल करने से पहले एक file के बारे में सवाल पूछते हैं।

In this page:

  1. File Tests

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

perl
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
{# 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. -e (exists) को -f (plain file) से confuse करना
  2. यह मान लेना कि -s एक empty file के लिए true return करता है
  3. एक 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:

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.