Here's the code, derived from examples/network/bot_irc.p6 in the pugs sources. Suggestions to make it more perl6ish welcome!
#!/usr/bin/pugs
use v6;
my $nick = "shakti";
my $server = "irc.freenode.net";
my $chan = "#mandrivafr";
my %karma;
my %sux = (
php => 1,
python => 1,
);
my %rulz = (
perl => 1,
perl6 => 1,
);
my $karmafile = '/tmp/shakti.dump';
sub dump_karma {
my $fh = open($karmafile,:w) err say "Can't open $karmafile";
$fh.say("$_:%karma{$_}") for keys %karma;
$fh.close;
}
# load karma
my $fh = open $karmafile err die "Can't load $karmafile";
for =$fh {
$_.= chomp;
my ($k, $v) = split ":", $_;
%karma{$k} = $v;
}
$fh.close;
my $hdl = connect($server, 6667);
say "Connected to $server";
$hdl.say("NICK $nick\nUSER $nick $nick $nick $nick");
$hdl.flush;
# discard first line
my $ligne = readline($hdl);
$hdl.say("JOIN $chan");
$hdl.flush;
say "Joined $chan";
while $ligne = =$hdl {
$ligne.= chomp;
given $ligne {
when rx:perl5/^PING/ {
$hdl.say("PONG $nick");
$hdl.flush;
}
when rx:perl5/^:(.*?)!.*? PRIVMSG $chan (.*)/ {
my $nick = $0;
my $msg = $1;
given $msg {
when rx:perl5/(\w+)\+\+/ {
if $nick eq $0 {
$hdl.say("PRIVMSG $chan:$nick: you can't up your own karma!");
}
else {
%karma{lc $0}++;
say "increment $0";
dump_karma();
}
}
when rx:perl5/(\w+)--/ {
%karma{lc $0}--;
say "decrement $0";
dump_karma();
}
when rx:perl5/\bkarma\s+(\w+)/ {
if $0 eq "shakti" {
$hdl.say("PRIVMSG $chan:I have infinite karma");
}
elsif %sux{lc $0} {
$hdl.say("PRIVMSG $chan:$0 has very, very bad karma");
}
elsif %rulz{lc $0} {
$hdl.say("PRIVMSG $chan:$0 has infinite karma");
}
elsif %karma{lc $0} {
$hdl.say("PRIVMSG $chan:$0 has karma of " ~ %karma{lc $0});
}
else {
$hdl.say("PRIVMSG $chan:$0 has neutral karma");
}
$hdl.flush;
}
}
}
};
}
Very readable (Score:2)
-Dom
Re:Very readable (Score:2)
Meanwhile, I was pointed out a few obvious mistakes; like two variables named $nick.
Hashes (Score:1)
I think you can use the named option syntax to more concisely initialize hashes where you want the values to be true:
I can't remember whether commas are needed, but I think not.
Also, there's probably a better way of iterating through a hash's keys and values together, though I'm not sure it'll work with the statement modifier variant of
forthat you're using.Smylers