factoids: allow querying definitions by number

This commit is contained in:
Přemysl Eric Janouch 2016-02-29 03:11:33 +01:00
parent f492592735
commit fb0b0c4cf0
1 changed files with 30 additions and 12 deletions

View File

@ -72,9 +72,11 @@ my %db = %{db_load $db_path};
sub learn {
my ($respond, $input) = @_;
return &$respond("usage: <name> = <definition>")
unless $input =~ /^([^=]+?)\s*=\s*(.+?)\s*$/;
unless $input =~ /^([^=]+?)(?:\s+(\d+))?\s*=\s*(.+?)\s*$/;
my ($name, $definition) = ($1, $2);
my ($name, $number, $definition) = ($1, $2, $3);
return &$respond("trailing numbers in names are disallowed")
if defined $2;
$db{$name} = [] unless exists $db{$name};
my $entries = $db{$name};
@ -86,6 +88,19 @@ sub learn {
db_save $db_path, \%db;
}
sub check_number {
my ($respond, $name, $number) = @_;
my $entries = $db{$name};
if ($number > @$entries) {
&$respond(qq/"$name" has only ${\scalar @$entries} definitions/);
} elsif (not $number) {
&$respond("number must not be zero");
} else {
return 1;
}
return 0;
}
sub forget {
my ($respond, $input) = @_;
return &$respond("usage: <name> <number>")
@ -96,10 +111,7 @@ sub forget {
unless exists $db{$name};
my $entries = $db{$name};
return &$respond(qq/"$name" has only ${\scalar @$entries} definitions/)
if $number > @$entries;
return &$respond("number must not be zero")
unless $number;
return unless check_number $respond, $name, $number;
splice @$entries, --$number, 1;
&$respond("forgotten");
@ -108,16 +120,22 @@ sub forget {
sub whatis {
my ($respond, $input) = @_;
return &$respond("usage: <name>")
unless $input =~ /^([^=]+?)\s*$/;
return &$respond("usage: <name> [<number>]")
unless $input =~ /^([^=]+?)(?:\s+(\d+))?\s*$/;
my ($name) = ($1);
my ($name, $number) = ($1, $2);
return &$respond(qq/"$name" is undefined/)
unless exists $db{$name};
my $i = 1;
my $definition = join ", ", map { "#${\$i++} $_" } @{$db{$name}};
&$respond(qq/"$name" is $definition/);
my $entries = $db{$name};
if (defined $number) {
return unless check_number $respond, $name, $number;
&$respond(qq/"$name" is #$number $entries->[$number - 1]/);
} else {
my $i = 1;
my $definition = join ", ", map { "#${\$i++} $_" } @{$entries};
&$respond(qq/"$name" is $definition/);
}
}
sub wildcard {