1

我这里有一个工作代码,它适用于 8 或 10 封电子邮件,但如果你只放 20 封电子邮件,它永远不会完成计算。也就是说,它不是一个无限循环,否则它永远不会计算任何东西。此外,如果您只使用 10 封电子邮件,但要求它列出超过 2 封电子邮件,同样的事情也会发生。是的,正如所指出的,有一段时间(@address),并且在某个地方,推入地址,这就是原因。我试图用另一个名字替换它被推送到的那个数组,但是我得到了奇怪的错误,比如它从列表中选择了一封电子邮件,它会抱怨虽然严格引用是打开的,但我不能使用它......我理解 100%直到'map'行的代码。之后就没那么多了...

如果我们看这部分:

push @addresses, $address;
    $moved{$address}++;
#     say "pushing $address to moved"; # debug

有人会说变量 $address 必须被推入,而不是推入@addresses,因为那是数据的来源(因此指出了循环),而是推到 ..'moved' 但是,对不起,'moved' 是一个哈希。您不能将变量推送到哈希中,可以吗?那么“移动”实际上应该是一个数组而不是一个散列吗?这就是我迷路的地方

我正在考虑这个,但是......这只是直觉,而不是真正的知识

push @{ $moved[$i] }, $address
4

2 回答 2

0

我想我已经解决了它,以“Konerak”的评论为出发点。事实上,这个问题是一个从未减少的清单。因为我对参考数组不了解,所以我有点迷茫,但是以某种方式阅读了我试图在预期行为中找到相似性的代码。

因此,我创建了另一个名为 @reserva 的数组并写了这个:

push @ {$reserva [$i]}, $address 

代替

 push @addresses, $address;

现在,无论我输入多少封电子邮件,我都会得到所需大小的列表。我尝试了 1000 次,不到一秒钟就没有问题。

所以,这是完整的代码

use strict;
use warnings;
use feature 'say';
use Data::Dumper;

my $only_index = 3; # Read from command line with $ARGV[0] or use Getopt::Long

my %blacklist = (       # Each key in this hash represents one index/day
  '2' => [ 'a', 'b' ],  # and has an arrayref of domains that have replied on
  '3' => [ 'c' ],       # that day. We look at all keys smaller than the current
);                      # index in each iteration and ignore all these domains 

my @domains; # holds the domains we have already seen for each list
my @lists = ([]); # Holds all the lists
my %moved; # the addresses we moved to the back
my $i = 0;
my @addresses = <DATA>;

while (@addresses) {
  my $address = shift @addresses;
  chomp $address;
  $address =~ m/@([a-zA-Z0-9\-.]*)\b/;
  my $domain = $1;

  # If the domain has answered, do not do it again 
  next if 
    grep { /$domain/ } 
    map { exists $blacklist{$_} ? @{ $blacklist{$_} } : () }  (0..$i);
  $i++ if (@{ $lists[$i] } == 2 
           || (exists $moved{$address} && @addresses < 1));
  if (exists $domains[$i]->{$domain}) {
    push @addresses, $address;
    $moved{$address}++;
#     say "pushing $address to moved"; # debug
  } else {
    $domains[$i]->{$domain}++;
    # send the email
#     say "added $address to $i";      # debug
    push @{ $lists[$i] }, $address;
  }
}
# print Dumper \@lists;           # Show all lists
print Dumper $lists[$only_index]; # Only show the selected list
1;


__DATA__
1@a
2@a
3@a
1@b
2@b
1@c
2@c
3@c
1@d
2@d
3@d
4@d
1@e
1@f
1@g
1@h
4@a
5@a
4@c
于 2012-07-22T08:50:28.013 回答
0

那是一些曲折的代码,难怪您在遵循它时遇到了麻烦。我实际上不确定代码的主体应该完成什么,但您至少可以通过不使用while (@array)- useforeach my $item (@array)来避免无限循环,您将对其进行迭代并避免因修改而产生的奇怪行为循环内的数组。

chomp(@addresses);  # chomp called on an array chomps each element 
foreach my $address (@addresses) {
    # Do work here
}
于 2012-07-23T15:24:51.073 回答