Perl合并文本的一段執行個體代碼_perl

來源:互聯網
上載者:User

有這樣一個文字檔,內容有多行如下,數量不定。
Lif(__amscript_cd("www.jb51.net")){__amscript_wc('#closead {display:none;}');};
Lif(__amscript_cd("www.jb51.net")){__amscript_wc('#footer_win {display:none;}');};
Lif(__amscript_cd("www.jb51.net")){__amscript_wc('.mainad {display:none;}');};
Lif(__amscript_cd("www.jb51.net")){__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.jb51.net")){__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();

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.