Inspired by a video on youtube
I wrote a calculator with Perl:
Beware the line my ($num1, $num2, $operator) = '@';
should be my ($num1, $num2, $operator) = @;
But the markdown syntax needs to have the @ into quotes otherwise, well the rest of the program is missing
#!/usr/bin/perl
# calculator
#
use strict;
use warnings;
sub get_input {
print "Enter number 1: ";
chomp(my $num1 = <STDIN>);
print "Enter number 2: ";
chomp(my $num2 = <STDIN>);
print "Enter operator (+, -, *, /): ";
chomp(my $operator = <STDIN>);
return ($num1, $num2, $operator);
}
sub calculate {
my ($num1, $num2, $operator) = '@'_;
my $result;
if ($operator eq '+') {
$result = $num1 + $num2;
} elsif ($operator eq '-') {
$result = $num1 - $num2;
} elsif ($operator eq '*') {
$result = $num1 * $num2;
} elsif ($operator eq '/') {
if ($num2 == 0) {
die "Error: Division by zero\n";
}
$result = $num1 / $num2;
} else {
die "Invalid operator\n";
}
return $result;
}
# Get input from the user
my ($num1, $num2, $operator) = get_input();
# Calculate the result
my $result = calculate($num1, $num2, $operator);
# Print the result
print "$num1 $operator $num2 = $result\n";
originally posted at