Perl 程式設計/檔案控制代碼
外觀
此方法將整個檔案讀入一個數組。 它將根據特殊變數進行分割$/
# Create a read-only file handle for foo.txt
open (my $fh, '<', 'foo.txt');
# Read the lines into the array @lines
my @lines=<$fh>;
# Print out the whole array of lines
print @lines;
此方法將逐行讀取檔案。 這將減少記憶體使用量,但程式必須在每次迭代時輪詢輸入流。
# Create a read-only file handle for foo.txt
open (my $fh, '<', 'foo.txt');
# Iterate over each line, saving the line to the scalar variable $line
while (my $line = <$fh>) {
# Print out the current line from foo.txt
print $line;
}
使用IO::File,您可以獲得更現代的 Perl 檔案控制代碼的面向物件介面。
# Include IO::File that will give you the interface
use IO::File;
# Create a read-only file handle for foo.txt
my $fh = IO::File->new('foo.txt', 'r');
# Iterate over each line, saving the line to the scalar variable $line
while (my $line = $fh->getline) {
# Print out the current line from foo.txt
print $line;
}
# Include IO::File that will give you the interface
use IO::File;
# Create a read-only file handle for foo.txt
my $fh = IO::File->new('foo.txt', 'r');
my @lines = $fh->getlines;
# Print out the current line from foo.txt
print @lines;