有这样一个文本文件,内容有多行如下,数量不定。
Lif(__amscript_cd("www.zzvips.com")){__amscript_wc('#closead {display:none;}');};
Lif(__amscript_cd("www.zzvips.com")){__amscript_wc('#footer_win {display:none;}');};
Lif(__amscript_cd("www.zzvips.com")){__amscript_wc('.mainad {display:none;}');};
Lif(__amscript_cd("www.zzvips.com")){__amscript_wc('.mt5.recommend {display:none;}');};
Lif(__amscript_cd("zzvips.com")){__amscript_wc('.ggAD {display:none;}');};
Lif(__amscript_cd("zzvips.com")){__amscript_wc('.ggSideBox {display:none;}');};
…………
要求合并为:
Lif(__amscript_cd("www.zzvips.com")){__amscript_wc('#closead, #footer_win, .mainad, .mt5.recommend {display:none;}');};
Lif(__amscript_cd("zzvips.com")){__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();