如何在 Perl 中检查文件是否存在?
在本教程中,我们将通过几个示例演示如何使用 Perl 检查文件是否存在。假设我们有一个名为“sample.txt”的简单文本文件,其中包含以下数据:
This is a sample txt file that contains some content inside it. TutorialsPoint is simply amazing!
我们将使用 Perl 代码来检查此文件是否存在。
示例 1
检查文件是否存在的最基本方法是使用“-e”标志,然后传递文件名。请考虑以下代码。
use warnings; use strict; my $filename = 'sample.txt'; if (-e $filename) { print "the file exists\n"; } else { print "the file does not exist!\n"; }
将程序代码保存为“sample.pl”,然后使用以下命令运行代码:
perl sample.pl
示例 2
我们还可以添加更具体的案例来检查文件是否包含任何数据,如果它存在的话。在下面的示例中,我们将检查这两种情况,并使用最少的代码量。“-s”标志在代码中可以帮助我们做到这一点。
use warnings; use strict; my $filename = 'sample.txt'; if (-e $filename) { print "the file exists\n"; } else { print "the file does not exist!\n"; } if (-s $filename) { print "the file exists and contains some data inside it\n"; } else { print "the file exists but doesn't contain any data inside it\n"; }
再次,将文件保存为“sample.pl”并使用以下命令运行它
perl sample.pl
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
结论
除了“-e”和“-s”之外,还有其他标志,例如“-r”用于检查文件是否可读,“-x”用于检查文件是否可执行,“-d”用于检查文件是否为目录,等等。在本教程中,我们使用了两个简单的示例来展示如何使用 Perl 代码来检查文件是否存在。
广告