You're right. Bitwise operators are the only place where there's a difference between strings and numbers. BTW This difference does not fit into the philosophy of Perl, where you should not be able to distinguish between strings and numbers, so this is actually a language design flaw.
You could detect if a scalar is a string or a number, without resorting to XS, by making use of this different behavior. If you use bitwise XOR (^) and XOR a scalar with itself, you'll get the value 0 if it was a number, and a string of null bytes ("\0") with the original string length of the argument, if it was a string. Yes, even if the number doesn't fit into an integer, like 1E99.
I think this will work:
sub is_number {
my $arg = shift;
return defined $arg && !ref $arg && ($arg^$arg) eq '0';
}
BTW dual-vars, like !1, are treated as a number.
-
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.
|