#!/usr/bin/perl -n
BEGIN{
die "Please give a file...\n" if ! @ARGV;
}
sub send_mail {
my($to, $from, $subject, @body) = @_;
use Net::SMTP;
my $relay = "127.0.0.1";
my $smtp = Net::SMTP->new($relay)
|| die "Can't open mail connection: $!";
$smtp->mail($from);
$smtp->to($to);
$smtp->data();
$smtp->datasend("To: $to\n");
$smtp->datasend("From: $from\n");
$smtp->datasend("Subject: $subject\n");
$smtp->datasend("\n");
foreach $body (@body) {
$smtp->datasend("$body\n");
}
$smtp->dataend();
$smtp->quit();
}
if(/^"\s*(.*)\s*"\s*,\s*"\s*(.*@.*)\s*"\s*$/){
$nomes[$. - 1]=$1;
$mail[$. - 1]=$2;
$nomes[$. - 1]=~s/\\(.)/$1/g;
}
END{
my %hash;
my @nomes2=@nomes;
#foreach(0 .. 3){
foreach(0 .. $#nomes2){
$num=int rand( $#nomes2 ) - 1;
($nomes2[$num],$nomes2[$_])=($nomes2[$_],$nomes2[$num]);
}
#}
foreach(0 .. $#nomes2){
if($nomes2[$_] eq $nomes[$_] || $nomes2[$num] eq $nomes[$num]){
($nomes2[$_-1],$nomes2[$_])=($nomes2[$_],$nomes2[$_-1])
if $_ > 0;
($nomes2[$_+1],$nomes2[$_])=($nomes2[$_],$nomes2[$_+1]) if $_ == 0;
}
}
foreach(0 .. $#nomes){
$from='santa@secretsanta.com';
$to=$mail[$_];
$sub="Automated Secret Santa";
$msg="Your santa is: ".$nomes2[$_]."\n";
print "To: $to\nFrom: $from\nSubject: $sub\nData: $msg\n\n";
send_mail($to, $from, $sub, $msg);
}
}
As has been pointed out, if you only need one derangement, it's better to simply shuffle the array (as you're doing - FY) and then simply rotate the copy.
/^"\s*(.*)\s*"\s*,\s*"\s*(.*@.*)\s*"\s*$/; $nomes[$. - 1]=$1; $mail[$. - 1]=$2; $nomes[$. - 1]=~s/\\(.)/$1/g;Never use $1 except in the context of knowing that you had a successful match. If the match fails, you'll get a stale $1, and that could ruin your day. In this case, if the match should never fail, add an "or die" to the match line.
-- [http://www.stonehenge.com/merlyn/|Randal L. Schwartz, Perl hacker]
Be sure to read [id://205373|my standard disclaimer] if this is a reply.
perlmonks.org content © perlmonks.org and jdporter, merlyn, smokemachine
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03