Skip to content

Instantly share code, notes, and snippets.

@jef-sure
Last active May 10, 2020 09:55
Show Gist options
  • Save jef-sure/378c26b3ac2bafc5b27ae14aaaacf5d2 to your computer and use it in GitHub Desktop.
Save jef-sure/378c26b3ac2bafc5b27ae14aaaacf5d2 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use v5.14;
my $input_string;
say "Hello! Input string as \"x + y\" or \"sin x\" \n";
say 'You can use "+", "-", "*", "\", "**", "sin", "cos", "tan"';
$input_string = <STDIN>;
my ($first_arg, $second_arg, $third_arg) = split ' ', $input_string;
my %algebra = (
'+' => sub {$first_arg + $third_arg},
'-' => sub {$first_arg - $third_arg},
'*' => sub {$first_arg * $third_arg},
'/' => sub {$first_arg / $third_arg},
'**' => sub {$first_arg**$third_arg},
);
my %trigonometry;
%trigonometry = (
'sin' => sub {sin $second_arg},
'cos' => sub {cos $second_arg},
'tan' => sub {$trigonometry{sin}->() / $trigonometry{cos}->()},
);
sub algebra {$algebra{$second_arg}}
sub trigonometry {$trigonometry{$first_arg}}
sub wrong_op {
sub {"The string entered in the incorrect form."}
}
my $op = ($input_string =~ m/^\d/ ? algebra() : trigonometry()) || wrong_op();
say $op->();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment