Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculate.pl Not working correctly. Please help - Newbie

Status
Not open for further replies.

hg4372

Technical User
Feb 9, 2009
43
0
0
US
I have a script that allows the user to input the following:

EQUALS
CLEAR
PLUS
MINUS
OVER
TIMES

But I run the script then type PLUS 42, it actually makes the value 43.

Please help

#!/usr/bin/perl
use strict;
use warnings;

my $value;

print "\n> ";

while ( <> ) {
chomp;
if ( /^CLEAR$/ ) { $value = 0; }
elsif ( /^EQUALS$/ ) {
if ( defined $value ) {
print "\n = $value\n";
}
else { print "\n (undefined)\n"; }
}
elsif (defined $value && /^PLUS|^MINUS|^TIMES|^OVER/ ) {
$value = compute($value);
}
else {
print "\nInvalid Statement\n";
}
print "\nOK\n";
print "\n> ";
}

sub compute {
my $num = @_;
print "\nNum is: $num\n";
if ( /^PLUS\s([0-9]+)/ ) {
$num += $1;
}
elsif ( /^MINUS\s([0-9]+)/ ) {
$num -= $1;
}
elsif ( /^TIMES\s([0-9]+)/ ) {
$num *= $1;
}
elsif ( /^OVER\s([0-9]+)/ ) {
$num /= $1;
}
return $num;
}
 
Hi

Perl:
[gray]# logically wrong[/gray]
[b]my[/b] [navy]$num[/navy] [teal]=[/teal] [navy]@_[/navy][teal];[/teal]      [gray]# set a scalar to an array == set it to the array's length[/gray]

[gray]# either correct[/gray]
[b]my[/b] [navy]$num[/navy] [teal]=[/teal] [navy]$_[/navy][teal][[/teal][purple]0[/purple][teal]];[/teal]   [gray]# set it to the first parameter[/gray]
[b]my[/b] [navy]$num[/navy] [teal]=[/teal] [b]shift[/b][teal];[/teal]   [gray]# extract first parameter from parameter list and set to it[/gray]

Next time please post your code between [tt][ignore]
Code:
[/ignore][/tt] and [tt][ignore]
[/ignore][/tt] TGML tags.

Please choose an Indent style and use it consistently.

Feherke.
[link feherke.github.com/][/url]
 
Thanks for the quick response. Sorry I didn't use
Code:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top