跳轉到內容

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;
前一頁: 高階輸出 索引 下一頁: 修飾符
華夏公益教科書