從檔案中讀取

my $filename = '/path/to/file';

open my $fh, '<', $filename or die "Failed to open file: $filename"; 
    
# You can then either read the file one line at a time...
while(chomp(my $line = <$fh>)) {
    print $line . "\n";
}

# ...or read whole file into an array in one go
chomp(my @fileArray = <$fh>); 

如果你知道輸入檔案是 UTF-8,則可以指定編碼:

open my $fh, '<:encoding(utf8)', $filename or die "Failed to open file: $filename";

從檔案讀完後,應該關閉檔案控制代碼:

close $fh or warn "close failed: $!";

另請參閱: 將檔案讀入變數

讀取檔案的另一種更快的方法是使用 File::Slurper Module。如果你使用許多檔案,這將非常有用。

use File::Slurper;
my $file = read_text("path/to/file"); # utf8 without CRLF transforms by default
print $file; #Contains the file body

另請參閱: [使用 slurp 讀取檔案]