Hello Monks!

As we all know, there is no real "number" or "string" data type in Perl, and Perl usually does The Right Thing depending on the context:

$x=15; $x.=4; $x+=2; # ==> 156
I am now looking for an elegant way of exploiting this in my program, in the following way:

I would like to compare two values for equality so that, iff Perl would agree to see them as a number, numerical equality should be used (i.e. '0' and '000' should be regarded equal), but if at least one of them is not a number, string equality should be used.

The only solution I came up with is very ugly and goes roughly like this:

$temp1=eval { 0+$value1 }; $temp1=$value1 if $@; Perl says it is not a number $temp2=eval { 0+$value2 }; $temp2=$value2; # By virtue of eval, we can now use string equality # even if the values were numbers before. if ($temp1 eq $temp2) { ... }
Needless to say that this is extremely awful. Of course one might argue that what I want to achieve is a bit weird too, but still I would like to know whether there is an easy way to do it. Basically, I'm looking for an operation which would leave a string unchanged, but normalizes a number so that for example '001' would turn into '1' (this would be done by my addition of zero for instance).

-- 
Ronald Fischer <ynnor@mm.st>

In reply to Exploiting Perls idea of what is a number by rovf

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.