
FishMonger
Veteran
/ Moderator
Jun 17, 2009, 8:17 AM
Post #4 of 16
(5830 views)
|
Re: [bclark8923] Teaching myself some basic perl
[In reply to]
|
Can't Post
|
|
You're welcome. BTW, even though the script is working, it does have some issues. 1) You need to add the strict pragma and create lexical vars by declaring them with the my keyword.
use warnings; use strict; #read in values print"Enter First Number: "; chomp(my $first = <STDIN>); 2) The separate vars for the operators is "ok", but it "forces" you to use that messy if/elsif/else block. You should use a hash instead of the separate vars.
my %operators = ( '+' => 'add', '-' => 'subtract', '*' => 'multiply', '/' => 'divide', ); Now, you can drop each of the elsif sections and have a simple if/else block. Your script is a pretty standard homework assignment and I normally don't provide complete answers to homework assignments. However, I'll take you at your word that this is a self taught exercise and not a school homework assignment.
#!/usr/bin/perl use warnings; use strict; print"Enter First Number: "; chomp(my $first = <STDIN>); print"Enter Second Number: "; chomp(my $second = <STDIN>); print"Enter +, -, *, or /: "; chomp(my $operator = <STDIN>); print"Enter Third Number: "; chomp(my $third = <STDIN>); my %operators = ( '+' => 'add', '-' => 'subtract', '*' => 'multiply', '/' => 'divide', ); if ( exists $operators{$operator} ) { my $equation = $first . $operator . $second; my $result = eval $equation; print"Does $first $operator $second equal $third?\n"; print $result == $third ? "yes\n" : "no, it equals $result\n"; } else { print"error"; }
|