Perl合并文本的一段實例代碼
有這樣一個文本文件,內容有多行如下,數量不定。
Lif(__amscript_cd("www.dhdzp.com")){__amscript_wc('#closead {display:none;}');};
Lif(__amscript_cd("www.dhdzp.com")){__amscript_wc('#footer_win {display:none;}');};
Lif(__amscript_cd("www.dhdzp.com")){__amscript_wc('.mainad {display:none;}');};
Lif(__amscript_cd("www.dhdzp.com")){__amscript_wc('.mt5.recommend {display:none;}');};
Lif(__amscript_cd("jbxue.net")){__amscript_wc('.ggAD {display:none;}');};
Lif(__amscript_cd("jbxue.net")){__amscript_wc('.ggSideBox {display:none;}');};
…………
要求合并為:
Lif(__amscript_cd("www.dhdzp.com")){__amscript_wc('#closead, #footer_win, .mainad, .mt5.recommend {display:none;}');};
Lif(__amscript_cd("jbxue.net")){__amscript_wc('.ggAD, .ggSideBox {display:none;}');};
思路:可以將url視為key,而將合并的字符串視為value,這樣存儲下來,在打印即可。只是打印的時候有點麻煩,因為這個字符串里面包含了單引號,雙引號,小括弧和花括弧,用q##做為字符串界定符即可。
#!/usr/bin/perl
use strict;
use warnings;
sub test {
my %comments_of_url = ();
open FILE, "<D:/Codesnippets/Perl/abc.txt" or die $!;
while (<FILE>) {
# Skip empty lines
next if /^\s*$/;
# Use url as key and #xxx as value for each line
# Merge all the #xxx for a url
if (/amscript_cd\("(.*?)"\)\){__amscript_wc\('(.*?)\s+\{/) {
$comments_of_url{ $1 } .= ( $2 . ',' );
}
}
foreach my $key (keys %comments_of_url) {
chomp (my $value = $comments_of_url{$key});
print q{Lif(__amscript_cd("};
print $key;
print q#")){__amscript_wc('#;
print $value;
print q#{display:none;}');};#;
print "\n";
}
}
sub main {
&test();
}
&main();
相關文章
Windows10下安裝配置 perl 環(huán)境的詳細教程
Perl 最重要的特性是Perl內部集成了正則表達式的功能,以及巨大的第三方代碼庫CPAN。這篇文章主要介紹了Windows10下安裝配置 perl 環(huán)境的詳細教程,需要的朋友可以參考下2020-12-12
Perl使用nginx FastCGI環(huán)境做WEB開發(fā)實例
這篇文章主要介紹了Perl使用nginx FastCGI環(huán)境做WEB開發(fā)實例,實現了路由系統(tǒng)和模板系統(tǒng),需要的朋友可以參考下2014-06-06
perl uc,lc,ucfirst,lcfirst大小寫轉換函數
這篇文章主要介紹了perl 大小寫字母轉換函數,需要的朋友可以參考下2017-10-10

