Looks like homework, but you have done some work and asked for suggestions.
- Don't push when you can print.
- Usually better to make sub work on one number rather than an array of numbers.
- Always use strict and use warnings.
- You don't have to predeclare the sub -> Ok to put the loop on the input first.
- If I have a good name for the sub, I may not have to be too interested in how it works. With this ordering, I see right away what the program
is supposed to do.
My version:
use strict;
use warnings;
my @input = ( -222, -221, -21, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
+, 144 );
foreach my $int (@input)
{
print "$int " if isSumDigitsOdd($int);
}
print "\n";
sub isSumDigitsOdd
{
my $num = shift;
my $sum;
$sum += $_ foreach (split //, abs $num);
return ( $sum % 2 ); # return ( $sum & 1 ); would be fine also
}
#prints: -221 -21 1 1 3 5 21 34 89 144
Update:
1) The name "isSumDigitsOdd" was chosen for a reason. The "is" prefix is one convention for indicating that this returns a flag/boolean value (yes/no). I expect 1 true, 0 false, but tolerate any one bits as true and only all zeroes as false.
2) The foreach loop was also done for a reason..I was able to work in the idea that this expects ints by using $int as the iterator value.
All sorts of details wind up making a difference.
Also:
As an example, I have used the absolute value function abs but I could have used abs($_). Which is best? Does it matter?
I would write abs($_) or even abs $_ rather than just "abs" just to make things more clear even though the generated code is the same. Often there is some descriptive name other than just $_ and I use $_ for simple one line loops like above. Naming loop iterator variables is cheap and improves readability - do it often!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.