Re: [問題] 新手請問取代檔案內容的寫法

作者: LiloHuang (十年一刻)   2020-05-16 16:51:48
提供兩個方法,很久沒有寫 Perl 了,可能寫起來不是很好。
use strict;
use feature qw(switch);
no warnings qw(experimental::smartmatch);
# using LUT method
my %maps = ('NTU' => 112,
'NCTU' => 113,
'NTHU' => 114,
'NCU' => 115,
'NCKU' => 116);
my $str1 = "NTU NCU NCTU NTHU NCKU";
$str1 =~ s/(\w+)/$maps{$1}/g;
print $str1,$/;
# replacing string with function
sub convert {
given (shift)
{
when ('NTU') { return 112; }
when ('NCTU') { return 113; }
when ('NTHU') { return 114; }
when ('NCU') { return 115; }
when ('NCKU') { return 116; }
}
die 'invalid argument';
}
my $str2 = "NTU NCU NCTU NTHU NCKU";
$str2 =~ s/(\w+)/convert($1)/eg;
print $str2,$/;

Links booklink

Contact Us: admin [ a t ] ucptt.com