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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |