跳轉到內容

Raku 程式設計/檔案

來自華夏公益教科書

開始之前

[編輯 | 編輯原始碼]

檔案控制代碼

[編輯 | 編輯原始碼]

在 Raku 中,任何與檔案互動都透過檔案控制代碼進行。[註釋 1] 檔案控制代碼是外部檔案的內部名稱。open 函式建立了內部名稱和外部名稱之間的關聯,而 close 函式則打破這種關聯。某些 IO 控制代碼無需建立即可使用:$*OUT$*IN 分別連線到 STDOUT 和 STDIN,即標準輸出流和標準輸入流。您需要自己開啟其他所有檔案控制代碼。

始終記住,程式中任何指向檔案的路徑都相對於當前工作目錄

檔案操作:文字

[編輯 | 編輯原始碼]

開啟檔案以供讀取

[編輯 | 編輯原始碼]

要開啟檔案,我們需要為其建立一個檔案控制代碼。這僅僅意味著我們建立一個(標量)變數,它將從現在開始引用該檔案。使用兩個引數的語法是呼叫 open 函式的最常見方式:open PATHNAME, MODE - 其中 PATHNAME 是您要開啟的檔案的外部名稱,而 MODE 是訪問型別。如果成功,這將返回一個 IO 控制代碼物件,我們可以將其放入標量容器中

my $filename = "path/to/data.txt";
my $fh = open $filename, :r;

:r 以只讀模式開啟檔案。為簡潔起見,您可以省略 :r - 因為它是預設模式;並且,當然,可以將 PATHNAME 字串直接傳遞,而不是透過 $filename 變數傳遞。

一旦我們有了檔案控制代碼,我們就可以讀取檔案並對檔案執行其他操作。

新方法

[編輯 | 編輯原始碼]

改用 slurp 和 spurt,因為

"file.txt".IO.spurt: "file contents here";
"file.txt".IO.slurp.say; # «file contents here»

讀取開啟的檔案

[編輯 | 編輯原始碼]

最通用的檔案讀取方法是透過 open 函式建立與資源的連線,然後執行資料消費步驟,最後在開啟過程中接收到的檔案控制代碼上呼叫 close

my $fileName;
my $fileHandle;

$fileName   = "path/to/data.txt";
$fileHandle = open $fileName, :r;

# Read the file contents by the desiderated means.

$fileHandle.close;

要將檔案資料立即完全傳輸到程式中,可以使用 slurp 函式。通常,這包括將獲取的字串儲存到變數中以進行進一步操作。

my $fileName;
my $fileHandle;
my $fileContents;

$fileName   = "path/to/data.txt";
$fileHandle = open $fileName, :r;

# Read the complete file contents into a string.
$fileContents = $fileHandle.slurp;

$fileHandle.close;

如果由於面向行的程式設計任務或記憶體考慮而無法完全消耗資料,則可以透過 IO.lines 函式逐行讀取資料。

my $fileName;
my $fileHandle;

$fileName   = "path/to/data.txt";
$fileHandle = open $fileName, :r;

# Iterate the file line by line, each line stored in "$currentLine".
for $fileHandle.IO.lines -> $currentLine {
  # Utilize the "$currentLine" variable which holds a string.
}

$fileHandle.close;

檔案控制代碼的使用可以重複利用資源,但另一方面,它也要求程式設計師注意其管理。如果提供的優勢不值得這些開銷,則上述函式可以直接作用於用字串表示的檔名。

可以透過指定檔名作為字串並對其呼叫 IO.slurp 來讀取完整的檔案內容。

my $fileName;
my $fileContents;

$fileName     = "path/to/data.txt";
$fileContents = $fileName.IO.slurp;

如果這種面向物件的方案不符合您的風格,則等效的程式性變體是

my $fileName;
my $fileContents;

$fileName     = "path/to/data.txt";
$fileContents = slurp $fileName;

在相同模式下,檔案控制代碼的自由逐行處理包括

my $fileName;
my $fileContents;

$fileName = "path/to/data.txt";

for $fileName.IO.lines -> $line {
  # Utilize the "$currentLine" variable, which holds a string.
}

請記住,可以選擇在不將檔名儲存到變數的情況下插入檔名,這會進一步縮短上述程式碼段。相應地,傳輸完整的檔案內容可能會簡化為

my $fileContents = "path/to/data.txt".IO.slurp;

my $fileContents = slurp "path/to/data.txt";

為了以更細的粒度訪問檔案,Raku 當然提供了透過 readchars 函式檢索指定數量字元的功能,該函式接受要消耗的字元數並返回表示獲取資料的字串。

my $fileName;
my $fileHandle;
my $charactersFromFile;

$fileName   = "path/to/data.txt";
$fileHandle = open $fileName, :r;

# Read eight characters from the file into a string variable.
$charactersFromFile = $fileHandle.readchars(8);

# Perform some action with the "$charactersFromFile" variable.

$fileHandle.close;

寫入檔案

[編輯 | 編輯原始碼]

關閉檔案

[編輯 | 編輯原始碼]
  1. 泛化為IO 控制代碼,用於與其他 IO 物件(如流、套接字等)進行互動。

外部資源

[編輯 | 編輯原始碼]
華夏公益教科書