如何将一个文件中的行与另一个文件中的行匹配?

时间:2013-08-26 15:54:34

标签: perl string-matching

我知道这里有一些重大错误,但我是Perl的新手并希望做到以下几点:

查找all.css中包含unused.css中的行的所有行并执行一些逻辑。我的代码的结构方式,似乎我无法匹配:

  

if($ lineA =〜/ $ lineU /)all.css中的#if行包含在unused.css中的行

因为变量是单独定义的。

我如何构建程序以便能够将all.css中的行与unused.css中的行匹配?

我的节目如下:

#!/usr/bin/perl

use strict;
use warnings;

open(my $unused_handle,'<', "unused.css") or die $!;
open(my $all_handle,'<',"all.css") or die $!;
open(my $out, '>' ,'lean.css') or die $!;

my $lineU = q{};
my $lineA = q{};

print $out "$lineU";

while($lineU =<$unused_handle>) {

    print $out "$lineU";
    #print $out "$lineA";  Line One not printed from All
    while($lineA =<$all_handle>) {

        if ($lineA =~ m/$lineU/sxm) {

            print "Huza!\n";
        }

        else {
            print "No Match\n";
        }

    }

}

close ($unused_handle);
close ($all_handle);
close ($out);

print "Done!\n";

exit;

我的输入文件示例如下。

来自unused.css的示例行:

audio, canvas, video
audio:not([controls])
[hidden]
h6

来自all.css的示例行:

article, aside, details, figcaption, figure, footer, header, hgroup, nav, section, summary {
    display: block;
}
audio, canvas, video {
    display: inline-block;
    *display: inline;
    *zoom: 1;
}
audio:not([controls]) {
    display: none;
    height: 0;
}
[hidden] {
    display: none;
}

2 个答案:

答案 0 :(得分:1)

尝试:

if ($lineA =~ m/$lineU/sxm)

另外,请考虑文件中可能有不同的行结尾,以及在执行比较之前剥离行结尾。

最后,我希望您在启动while循环之前通过拉一行来识别您忽略每个文件的第一行。

my $lineU = <$unused>;
my $lineA = <$all>;

如果您不想这样做,最好按原样初始化:

my $lineU = q{};
my $lineA = q{};

答案 1 :(得分:1)

我希望这个(未经测试的)代码片段对您有所帮助:

#!/usr/bin/perl

use strict;
use warnings;

open(my $unused,'<', "unused.css") or die $!;
open(my $all,'<',"all.css") or die $!;

# store all lines of unused.css in a hash
my %unused_line;
while (<$unused>) {
    #remove newlines
    chomp();
    #store the line as a key with empty value
    %unused_line{$_}="";
}
close ($unused);

#...for every line in all.css
while (<$all>) {
    #have we seen it in unused.css (at least everything before ' {')
    if ((m/^(.*\S+)\{/) && (exists $unused_line{$1}))
    {
        #a match - found a line of unused.css in all.css
    }else{
        #no match  - line does not exists in unused.css
    }
}
close ($all);