作者Solberg (packing for trip)
看板Perl
標題[問題] 替換第一個空白為\t
時間Wed May 18 14:13:04 2016
各位版大好
小弟有段時間沒碰perl,最近作一個字串處理,要將每個字
第一個空白取代為tab(\t)
ex:
"紙盒 5x10x1" -> "紙盒 5x10x1"
我寫的程式如下
--------------------------------------------------------------
use strict;
use warnings;
my $filename = 'token'; //開檔案token
open(my $fh, $filename)
or die "Could not open file '$filename' $!";
while (my $row = <$fh>) {
chomp $row;
$row =~ s/^\S+\s/$1.\t/; //比對程式
print "$row\n";
}
--------------------------------------------------------------
但出現例外
Use of uninitialized value $1 in concatenation (.) or string at test.pl line 11,
<$fh> line 10.
我記得第一個比對到的字串不是會被存在變數$1裡嗎?
怎麼會uninitialized value?
或者,這樣的要求,有什麼更好的寫法嗎?感謝。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.252.34.40
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Perl/M.1463551986.A.938.html
1F:推 cutekid: $row =~ s/^(\S+)\s+/$1\t/; 05/18 15:01
2F:→ Solberg: 1樓版友,感謝你,ok了。 05/19 15:04