I read the posts from
Hippo and
LanX.
Instead of ignoring the
errors warnings from the int() function, the code to handle the basic cases is not much (shown below). Now instead of seeing warning stuff printed to the terminal, you have some "place holder if statements" where you could put calls to some logging program, etc for the various cases. It does indeed sound odd to convert "ABC" to numeric 0. Note that your code would not convert a blank string " " to zero because that string is logically true.
If I were debugging this code, I would do an experiment by just taking the call to int() out. Then of course int() can't issue a warning. Presumably that would result in the same type of "non-numeric value used in addition" somewhere else in the code. I would be interested in that code to help me understand why this weird conversion of string to numeric 0 is needed in the first place? Sometimes the immediate runtime error is not the "real" error.
use strict;
use warnings;
use feature 'say';
say force2integer(""); # 0
say force2integer(" "); # 0 # " " is actually True
say force2integer("abc"); # 0
say force2integer("a10.5"); # 0
say force2integer(12.5); # 12
say force2integer("13"); # 13
say force2integer("14XYZ"); # 0 (would be 14 with a warning)
say force2integer(undef); # 0
# Return 0 if the input cannot be converted to an
# integer without a warning.
# Does not consider malformed floats like: 10.1.2.
sub force2integer
{
my $val = shift;
return 0 unless defined $val;
return 0 if ($val =~ /[^0-9.]/); # imperfect float test
return 0 if ($val eq ""); # null is not numeric 0!
return int($val);
}
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.