Yes, you do need to use hex to explicitly convert a string containing a hexadecimal value.

This is because while the Perl parser can safely infer that the bare word 0x000a is a numeric constant expressed in hexadecimal because this is an established syntactic rule of the Perl language. However, Perl's run time string-to-number coercion doesn't make assumptions about a string not matching /^[0-9]/ because a string is just a string.

Perl also has oct to handle octal values.

However, there there is an important differnece between hex and oct. hex will only try to interpret the string as hexadecimal, skipping a leading '0x' if present. oct, on the other hand, if the string has a leading '0x' (or '0b'), will try to interpret the string as hexadecimal (or binary). Otherwise, it will try octal.

Using oct, you can create a simple, dumb converter that will handle decimal, hexadecimal and binary string to number conversion:

sub dhob2num { my $s = shift; if ($s =~ /^0/) { return oct($s); } # Note: should validate the stri +ng return ( 0 + $s ); }

While flexible and useful, this function is dumb because it doesn't validate the string to insure it is a proper number in the radix indicated by the prefix.


In reply to Re: sprintf to hash by RonW
in thread sprintf to hash by teamassociated

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.