我試圖創建一個簡單的腳本來讀取包含書名記錄的文本文件。每個記錄都用普通的舊雙空格分開(\r\n\r\n
)。我需要計算文件中有多少記錄。在Perl中使用CR/LF(回車符和換行符)分隔計數記錄
例如這裏輸入文件:
record 1
some text
record 2
some text
...
我使用正則表達式來檢查回車和新行,但不能匹配。我究竟做錯了什麼?我在我的智慧結束。
sub readInputFile {
my $inputFile = $_[0]; #read first argument from the commandline as fileName
open INPUTFILE, "+<", $inputFile or die $!; #Open File
my $singleLine;
my @singleRecord;
my $recordCounter = 0;
while (<INPUTFILE>) { # loop through the input file line-by-line
$singleLine = $_;
push(@singleRecord, $singleLine); # start adding each line to a record array
if ($singleLine =~ m/\r\n/) { # check for carriage return and new line
$recordCounter += 1;
createHashTable(@singleRecord); # send record make a hash table
@singleRecord =(); # empty the current record to start a new record
}
}
print "total records : $recordCounter \n";
close(INPUTFILE);
}
我剛剛纔知道白色空間匹配[\ t \ n \ f \ r]。超混淆。 這是我的修改後的代碼,其正確地計數我的記錄: 如果($ SINGLELINE =〜米/^\ S $ /){#檢查爲回車和換行 \t \t \t \t $ recordCounter ++; } – astra
你的新正則表達式只匹配一個字符。如果它有效,那麼你知道爲什麼試圖匹配兩個字符失敗。 –