2013-03-15 63 views
0

我想在stdin上以交互方式讀取記錄。 CTRL + D標記記錄的結尾。它會一直持續下去,直到按下ctrl + c。我的代碼產生以下錯誤:在STDIN上讀取記錄會產生未初始化的值錯誤

Use of uninitialized value in open 
Use of uninitialized value in <HANDLE> 

錯誤可以通過測試$ rec來避免,我必須這樣做才能跳過空記錄。但我覺得我掩蓋了一個我不太明白的問題。我懷疑stdin正在關閉,但我不確定。你能解釋爲什麼發生錯誤以及如何修復我的循環?

my $eof = $INPUT_RECORD_SEPARATOR; 
while (1) { 
    local $INPUT_RECORD_SEPARATOR = chr(0x04); 
    my $rec = <STDIN>; 

    # format last record that ended with ^D 
    local $INPUT_RECORD_SEPARATOR = $eof; 
    open my $input, "<", \$rec;  
    my_formatting_func $input; 
    close $input; 
} 
+0

Ctrl + D是EOF。 – choroba 2013-03-15 13:48:36

+0

'format'?在文件句柄上?你認爲這是什麼? – TLP 2013-03-15 13:49:44

+0

我想改變我的真實的功能名稱的東西。我沒有懷疑format是一個真正的perl函數。 – 2013-03-15 14:18:36

回答

0

您的代碼無論如何都不會工作,爲format預計的輸出文件句柄的名字和圖片格式作爲其參數,並且您正在使用的輸入文件句柄引用提供它。

但是,問題在於,在Perl程序看到它之前,control-D是由C庫處理的。它會導致流被關閉,隨後對readfile的調用將返回undef

只要寫

last unless defined $rec; 

,你會得到完整的輸入記錄。最重要的是,使用慣用的習慣用法並編寫

{ 
    my $eof = $INPUT_RECORD_SEPARATOR; 
    local $INPUT_RECORD_SEPARATOR; 
    while (my $rec = <STDIN>) { 
     local $INPUT_RECORD_SEPARATOR = $eof; 
     open my $input, "<", \$rec;  
     format $input; 
     close $input; 
    } 
} 
相關問題