Respected Monks,
Thank you for all your answers.
After seeing all the replies here, I too had the urge to try it out my way, so I threw away all the restrictions that the example had put and tried it my way, so that it will work for any numbers, positive or negative, decimal/hex/octal/binary, and came up with this.
use strict; use warnings; my @numbers = (10, 110, 24, 30, -17,-9,12,14,-011,-0xF,0b111,0); sub biggest_odd { my @odd_only = grep {$_ % 2 != 0} @_; if (!@odd_only) { print "No odd numbers at all\n"; return; } my $biggest_odd_num = shift @odd_only; foreach my $odd_num(@odd_only) { if ($odd_num > $biggest_odd_num) { $biggest_odd_num = $odd_num; } } print "Biggest odd is $biggest_odd_num\n"; } &biggest_odd(@numbers);
And here is the output:
C:perlscripts>perl jg_find_biggest_odd.pl Biggest odd is 7
Like I said earlier, I really love Perl, but I find the John Guttag book so interesting that I've started learning Python just so that I can understand the concepts given in the book. I don't know how much successful I will be learning two languages simultaneously, especially given the fact that I love the Perl way of solving problems...
In reply to Re: John Guttag's book - 2nd exercise. My attempt in Perl.
by pritesh_ugrankar
in thread John Guttag's book - 2nd exercise. My attempt in Perl.
by pritesh_ugrankar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |