Perl: code times out when given more than 10 lines to process
===

I have here a working code, which is to manage emails, selecting the domains and preventing from resending others from the same domain if recipient has answered. It works fine with 8 or 10 emails, but if you just put 20 emails it never finishes computing. That is, it is not an infinite loop because otherwise it would never compute anything. Also, if you use just 10 emails but ask it to make lists of more than 2, same thing happens. You can run it at codepad.org and will see that it just doesn't make it. Any of you expert in maths or algorithms know how to calculate how many permutations the program does?

    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 (finally, your map ;-))
      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

