in reply to Newbie question
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.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
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Newbie question
by jdporter (Paladin) on Aug 24, 2022 at 13:24 UTC | |
by oldB51 (Sexton) on Aug 24, 2022 at 13:35 UTC | |
|
Re^2: Newbie question
by oldB51 (Sexton) on Aug 23, 2022 at 12:41 UTC | |
by Marshall (Canon) on Aug 23, 2022 at 15:34 UTC | |
by oldB51 (Sexton) on Aug 23, 2022 at 16:08 UTC |