如何在 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

結論

除了“-e”和“-s”之外,還有其他標誌,例如“-r”用於檢查檔案是否可讀,“-x”用於檢查檔案是否可執行,“-d”用於檢查檔案是否為目錄,等等。在本教程中,我們使用了兩個簡單的示例來展示如何使用 Perl 程式碼來檢查檔案是否存在。

更新於: 2023-03-14

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.