rewrite Base.pm to use an "any" trigger instead of a regex
parent
7955f1bc85
commit
cb23593f2f
|
@ -1,17 +1,25 @@
|
|||
package DDG::Goodie::Base;
|
||||
use 5.010;
|
||||
use strict;
|
||||
use warnings;
|
||||
use Math::Int2Base qw/int2base/;
|
||||
use DDG::Goodie;
|
||||
|
||||
triggers query_clean => qr/^[0-9]+\s*(?:in|as)\s+(?:hex|octal|oct|binary|base\s*[0-9]+)$/;
|
||||
triggers any => qw/hex hexadecimal octal oct binary base/;
|
||||
|
||||
handle query_clean => sub {
|
||||
my ($number, undef, @rest) = split ' ', $_;
|
||||
my $base = $rest[0] eq 'hex' ? 16
|
||||
: ($rest[0] eq 'octal' || $rest[0] eq 'oct') ? 8
|
||||
: $rest[0] eq 'binary' ? 2
|
||||
: $rest[1];
|
||||
return unless /^([0-9]+)\s*(?:in|as)\s+(hex|hexadecimal|octal|oct|binary|base\s*([0-9]+))$/;
|
||||
my $number = $1;
|
||||
my $base = $3;
|
||||
unless (defined $base) {
|
||||
given ($2) {
|
||||
when ('hex' ) { $base = 16 }
|
||||
when ('hexadecimal') { $base = 16 }
|
||||
when ('oct' ) { $base = 8 }
|
||||
when ('octal' ) { $base = 8 }
|
||||
when ('binary' ) { $base = 2 }
|
||||
}
|
||||
}
|
||||
return if $base < 2 || $base > 36;
|
||||
my $based = int2base($number, $base);
|
||||
return "$number in base $base is $based";
|
||||
|
|
Loading…
Reference in New Issue