As an example, I have used the absolute value function abs but I could have used abs($_). Which is best? Does it matter?
It doesn't really matter which you use - either way, the same code gets executed.
Interestingly, there's no need to call on the abs() function at all.
You could replace:
my @digits = split //, abs;
with:
my @digits = split //, $_;
That will work fine because the "-" character evaluates to zero in numeric context, anyway.
With that change (and the other previously mentioned correction) in place, the script then outputs:
C:\_32\pscrpt>perl try.pl
Argument "-" isn't numeric in addition (+) at try.pl line 10.
Argument "-" isn't numeric in addition (+) at try.pl line 10.
Argument "-" isn't numeric in addition (+) at try.pl line 10.
-221 -21 1 1 3 5 21 34 89 144
The warnings can be silenced by inserting:
no warnings 'numeric';
into the oddDigitSum() subroutine:
sub oddDigitSum {
no warnings 'numeric';
my @ans;
for(@_) {
my @digits = split //, $_;
my $sum;
$sum += $_ for @digits;
$sum % 2 && push @ans, $_;
}
return @ans;
}
Note that any "numeric" warnings triggered from outside the oddDigitSum() subroutine are still enabled.
I'm not sure which approach is the most efficient - you could
use Benchmark; to find out, if you want.
I expect there's not much difference performance-wise.
Cheers,
Rob
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.