0

我编写了一个 perl 代码来处理以下内容的文件“Output.txt”。

  new.example.com 28
  new.example.com 28
  example.com 28
  example.com 29
  example.com 29
  example.com 29
  example.com 29
  orginal.com 28
  orginal.com 29
  orginal.com 30
  orginal.com 31
  expand.com  31

并且文件“domain.txt”具有我需要与文件“Output.txt”匹配的域名列表

new.example.com
example.com
orginal.com
test.com
new.com

我可以设法编写这样的PERL代码

#!/usr/bin/perl
use strict;
open(LOGFILE,"Output.txt") or die("Could not open log file.");
my $domain_name = 'domain.txt' ;
open(DOM, $domain_name);
my @r_contents = <LOGFILE>;
close(LOGFILE);    
while(<DOM>) {
    chomp;
    my $line = $_;
    my @lowercase = map { lc } @r_contents;
    my @grepNames = grep  /^$line/, @lowercase;
    foreach (@grepNames) {
        if ( grep  /^$line/, @lowercase ) {
            $domains{lc($_)}++ ;            }
    }
}

close(DOM) ;    
foreach my $domain (sort keys %domains) {
    my %seen ;
    ($Dname, $WeekNum) = split(/\s+/, $domain);
    my @array1 = grep { ! $seen{ $_ }++ } $WeekNum;
    push @array2, @array1;
    my @array4 = "$domains{$domain} $domain" ;
    push @matrix,@array4 ;
}
   printf "%-10s %-25s %-25s\n", 'DoaminName', "Week $array2[0]" ,"Week $array2[1]","Week $array2[2]";
   print " @matrix \n";

当前输出看起来像这样。

 DoaminName         Week 28        week29   week30  week 31
 2 new.example.com 35
 1 example.com 28
 4 example.com 29
 1 orginal.com 28
 1 orginal.com 29
 1 orginal.com 30
 1 orginal.com 31

但是我尝试重新编写 perl 代码来打印这样的输出。请帮助我更正代码。

Domain/WeekNumber   Week28       Week29        Week30        Week31
new.example.com     2            No            No            No
example.com         1            4             NO            NO
orginal.com         1            1              1             1
4

1 回答 1

1

这会产生所需的输出,只有我也对输出进行了排序。

如果您的网站名称很长,请根据需要在代码中添加选项卡。

#!/usr/bin/perl
use warnings;
use strict;
open my $fh, "<", "Output.txt" or die "could not open Output.txt\n";

my %data;
my %weeks;
while(<$fh>){
    chomp;
    $_=~ m/(.*?)\s++(\d++)/;
    my $site=$1;
    my $week=$2;
    $weeks{$week}++;
    $data{$site}{$week}++;
}

print "Domain/WeekNumber";

for my $week (sort {$a <=> $b} keys %weeks){
    print"\tWeek$week";
}
print"\n";

for my $site(sort keys %data){
    print"$site\t\t";
    for my $week (sort {$a <=> $b} keys %weeks){
            unless(defined $data{$site}{$week} ){
                    print"NO\t";
            }else{
                    print $data{$site}{$week} ."\t";
            }
    }
    print"\n";
}
close $fh;
于 2012-10-11T15:28:07.813 回答