aboutsummaryrefslogtreecommitdiff
path: root/Plugin/Convert.pm
diff options
context:
space:
mode:
Diffstat (limited to 'Plugin/Convert.pm')
-rwxr-xr-xPlugin/Convert.pm61
1 files changed, 41 insertions, 20 deletions
diff --git a/Plugin/Convert.pm b/Plugin/Convert.pm
index 75f4ba0..46af1e2 100755
--- a/Plugin/Convert.pm
+++ b/Plugin/Convert.pm
@@ -9,10 +9,42 @@ sub configure {
my $cmdref = shift;
$cmdref->($self, "convert", sub { $self->convert(@_); } );
+ $cmdref->($self, "define", sub { $self->define(@_); } );
return $self;
}
+sub convert_common {
+ my ($from, $to) = @_;
+
+ my ($out, $in, $pid);
+ my @command = (
+ 'units',
+ '-1',
+ '--compact',
+ '--quiet',
+ $from
+ );
+
+ if ($to) {
+ push @command, $to;
+ }
+
+ eval {
+ $pid = open2($out, $in, @command);
+ } or do {
+ return "Error: units command not installed";
+ };
+
+ my $output = <$out>;
+ chomp $output;
+ waitpid($pid, 0);
+ my $exit_status = $? >> 8;
+ return "Error: $output" if $exit_status;
+
+ return "$output"
+}
+
sub convert {
my ($self, $irc, $logger, $who, $where, $ided, $rest, $no_reenter, @arguments) = @_;
@@ -21,28 +53,17 @@ sub convert {
return "Syntax: convert <from> [to <to>]\n" unless ($from);
- my ($out, $in);
- my $pid;
- if ($to) {
- $pid = open2($out, $in, 'units', '-1', '--compact', '--quiet', $from, $to);
- } else {
- $pid = open2($out, $in, 'units', '-1', '--compact', '--quiet', $from);
- }
-
- my $converted = <$out>;
- chomp $converted;
+ my $converted = convert_common($from, $to);
+ return "Convert $from -> $to: $converted\n";
+}
- close($in);
- waitpid($pid, 0);
+sub define {
+ my ($self, $irc, $logger, $who, $where, $ided, $rest, $no_reenter, @arguments) = @_;
- my $exit_status = $? >> 8;
- # `units` doesn't actually seem to set this non-zero, but use it anyway
- return "Error: $converted" if $exit_status;
+ return "Syntax: define [unit/expression]\n" unless ($rest);
- if ($to) {
- return "Convert $from -> $to: $converted\n";
- } else {
- return "Define $from: $converted\n";
- }
+ my $defn = convert_common($rest, undef);
+ return "Define $rest: $defn\n";
}
+
1;