Perl IfThenElse problem
Hello, I was writting this code and i did the last part with
$max = $numbers[0]; $max= $_>$max ? $_ : $max foreach (@numbers); print ("the biggest number is $max\n"); now im trying to do it using if then else.. but i get errors. any ideas?? Code:
#!/usr/bin/perl |
It's called "elseif" in Perl - written in one word. (See perldoc perlsyn)
Code:
if ($foo eq "bar") { |
Quote:
Code:
#!/usr/bin/perl |
No.
I mean: Code:
if ($numbers[0] > $numbers[1]) { |
Code:
#!/usr/bin/perl -bash-3.00$ perl asng4.pl Enter the first number? 1 Enter the second number? 2 Enter the third number? 3 1 2 3 First number was 1 Second number was 2 Third number was 3 The Sum is 6 The product is 6 Can't locate object method "endif" via package "endif" (perhaps you forgot to load "endif"?) at asng4.pl line 39, <STDIN> line 3. this is just bad luck!.. |
1) You should always include warnings and strict.
2) You should chomp off the newlines from the numbers you get from STDIN. 3) There is no 'endif' in Perl. (Are you thinking of Bash?) 4) You don't need parentheses for such simple print statements. 5) The logic of your test for the largest number is faulty. What you wrote above is "If the first number is bigger than the second, then the first number is the largest." But you can't know which is the largest of three until you check them all. Also, you first test is $numbers[0] is larger than $numbers[1] and then you check if $numbers[1] is smaller than $numbers[0]. Those two tests do exactly the same thing in the opposite direction. I think you were trying to use a "high-water mark algorithm". Here's my quick version of something like that for you. Code:
#!/usr/bin/perl |
Quote:
|
Well, this would work, but it's an awfully silly way to find the largest of three numbers. (Try imagining this sort of thing for 40 or 50 numbers.)
Code:
if ( $numbers[0] > $numbers[1] ) { # Check if the first number is bigger than the second |
All times are GMT -5. The time now is 05:02 AM. |