※ 引述《RueyJing (瑞)》之銘言:
: 我真的是翻書和上網找資料找到快瘋了也找不到..
: 我想將文字檔案中的某些換行符號刪去..
: 例如:
: An apple a day , \n
: keeps the doctor away \n
: 我本來是寫
: while(<檔案>){
: chomp ;
: s/An apple a day , \nkeeps the doctor away/
: An apple a day ,keeps the doctor away/gm ;
: }
: 但是卻怎樣都沒辦法出現我想要的結果
: 我有想過要把chomp拿掉..可是拿掉就會出現error訊息..
: 請大家幫幫忙教一下啊..我快抓狂了..今天一整天都在想這個問題..
1. 先確定您的檔案要一行一行讀進來嗎?而且使用 \n 來區隔。
這樣 \n 只會在每行的最後面出現,經 chomp 處理完也應該不見了。
while (<ARGV>) {
#chomp;
print "[$_]";
}
2. 另外也可以考慮整個檔案都讀進來,再來做字串取代。
my $s = '';
READFILE: {
local $/;
$s = <ARGV>;
}
3. 確定字串中是否會包含 \n,選擇合適的正規表示法來處理。
使用 Perl regexp 中的 modifiers,如 x、m、s、g 等,
像是 s/pattern/replacement/xms 或 s/pattern/replacement/gm。
且記得正確處理空白與換行符號。
m Multiline mode - ^ and $ match internal lines
s match as a Single line - . matches \n
x eXtended legibility - free whitespace and comments
g Global - all occurrences
建議參考:
1. http://perldoc.perl.org/perlreref.html
2. perlre、perlreref
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.114.64.130
推
01/07 12:50, , 1F
01/07 12:50, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):