So, if I ask to convert "55a" then it returns "55" which is fine. But if I try to convert "a55" then it returns 0, which baffles me! It should return 55. Why does this happen?
This is simply how Perl's string-to-number conversion works, it only takes the first portion of the string that looks like a number (although interestingly, I'm having trouble finding a reference in the Perl documentation at the moment*). The tr/0-9//cd solution is one way to work around that, if you are ok with strings such as "a1b2c3.4d" being converted to 1234.
local $SIG{__WARN__}
Instead of trying to trap the warning, it's better to use looks_like_number from Scalar::Util, as this gives you the exact internal function that Perl uses to check strings and generate that warning in the first place. (Update 2: We've been over this before.)
* Update: The Camel says "To convert from string to number, Perl internally uses something like the C library’s atof(3) function.", and atof(3) says "The atof() function converts the initial portion of the string" (emphasis mine).
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|