I need to implement a fuction which will convert scalars in complex data structures from one character encoding to another (or from perl character string to binary string in a certain encoding). But I need to not-stringify numbers, bacause JSON::XS outputs numbers and strings different way. Looking for something like this:
$ perl -MB -E 'my $x = 1; say B::class(B::svref_2object(\$x)) eq "IV" +? "yes" : "no" ' yes $ perl -MB -E 'my $x = "1"; say B::class(B::svref_2object(\$x)) eq "IV +" ? "yes" : "no" ' no
but something fast. above implementation is very slow.
use strict; use warnings; use Benchmark qw/:all/; use B; use Scalar::Util qw/looks_like_number/; cmpthese(-1, { iv => sub { my $r; for my $var (1...1000) { $r = B::class(B::svref_2o +bject(\$var)) eq 'IV' } }, ref => sub { my $r; for my $var (1...1000) { $r = ref($var) eq '' } + }, lln => sub { my $r; for my $var (1...1000) { $r = Scalar::Util::looks +_like_number($var) } }, }); __END__ iv 806/s -- -93% -95% lln 12047/s 1394% -- -18% ref 14768/s 1732% 23% -- __END__ Rate iv lln ref iv 799/s -- -93% -95% lln 11821/s 1379% -- -20% ref 14768/s 1748% 25% --
Another possible way is to just use looks_like_number, because anything that looks_like_number is plain ASCII and should not be encoded/decoded. But I don't want to skip plain ASCII strings with numbers, with UTF-8 flag on, as several modules, that we use are affected by The Unicode Bug. So I prefer find solution like B::svref_2object

In reply to Fast way to distinc number vs string from Perl level by vsespb

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.