Perl merge text of a piece of example code


There is such a text file with multiple lines as follows, and the quantity is variable.
Lif(__amscript_cd(“”)){__amscript_wc(‘#closead {display:none;}’);};
Lif(__amscript_cd(“”)){__amscript_wc(‘#footer_win {display:none;}’);};
Lif(__amscript_cd(“”)){__amscript_wc(‘.mainad {display:none;}’);};
Lif(__amscript_cd(“”)){__amscript_wc(‘.mt5.recommend {display:none;}’);};
Lif(__amscript_cd(“”)){__amscript_wc(‘.ggAD {display:none;}’);};
Lif(__amscript_cd(“”)){__amscript_wc(‘.ggSideBox {display:none;}’);};
The requirements are combined into:
Lif(__amscript_cd(“”)){__amscript_wc(‘#closead, #footer_win, .mainad, .mt5.recommend {display:none;}’);};
Lif(__amscript_cd(“”)){__amscript_wc(‘.ggAD, .ggSideBox {display:none;}’);};

Idea: you can treat the URL as a key and the merged string as a value, which can be stored and printed. It’s just a little troublesome when printing, because the string contains single quotation marks, double quotation marks, small parentheses and flower parentheses, which can be used q## as the string delimiter.


Copy codeThe code is as follows:

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 {