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).


In reply to Re: Converting to number doesn't always work... (updated) by haukex
in thread Converting to number doesn't always work... by harangzsolt33

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.