华域联盟 perl Perl合并文本的一段实例代码

Perl合并文本的一段实例代码

有这样一个文本文件,内容有多行如下,数量不定。
Lif(__amscript_cd("www.cnhackhy.com")){__amscript_wc('#closead {display:none;}');};
Lif(__amscript_cd("www.cnhackhy.com")){__amscript_wc('#footer_win {display:none;}');};
Lif(__amscript_cd("www.cnhackhy.com")){__amscript_wc('.mainad {display:none;}');};
Lif(__amscript_cd("www.cnhackhy.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.cnhackhy.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();

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » Perl合并文本的一段实例代码

转载请保留出处和原文链接:https://www.cnhackhy.com/76660.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部