G'day oldB51,
Don't write "My code appears to work." and leave us to verify it; show your output. It didn't work for me because:
$ perl -e 'print “\n”;' Unrecognized character \xE2; marked by <-- HERE after print <-- HERE n +ear column 7 at -e line 1.
Using a subroutine is usually a good thing. It abstracts your code so it can be reused within your script. If you find it's particularly useful, you can put it in a module and many scripts can reuse it.
There are many functions whose default argument is $_. Writing abs instead of abs($_) is absolutely fine. Pun intended. :-)
Aim for readability and maintainability. The following might look clever but, for many, it would be difficult to understand; it's not easy to modify; and, it can't be reused.
#!/usr/bin/env perl use strict; use warnings; use List::Util 'sum'; my @input = qw{-222 -221 -21 0 1 1 2 3 5 8 13 21 34 55 89 144}; print join(' ', map +(sum(split //, abs) % 2 ? $_ : ()), @input), "\n" +;
Output:
-221 -21 1 1 3 5 21 34 89 144
Always use the strict and warnings pragmata. You may get one or both of those for free, with different values of VERSION, if you "use VERSION;". Some modules also do this for you.
I would also recommend that you unpack @_ at the start of your subroutines. There are other variables that you should deal with as soon as they become available; for example, $@ containing errors; $1, $2, and so on from regex matches; etc. There are various things that can change their values, perhaps not in the code when first written, but via insidious bugs that might be introduced following modifications. The following would've been better:
sub oddDigitSum { my (@nums) = @_; my @ans; for (@nums) { ...
Of course, all of the above are my opinions. Others may have different opinions. Form you own opinions as your experience grows. :-)
— Ken
In reply to Re: Newbie question
by kcott
in thread Newbie question
by oldB51
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |