SibiCoder SibiCoder - 8 months ago 18
Perl Question

Sprintf in Perl doesn't display hexadecimal character properly

I have a code like this.

$entry = &function(); //returns a number between 0 to 20
$var = sprintf("%#.4x", $entry);
if($var=~ /$hex/)
//block of statements

$hex will be within 0x0000 ..... 0x0014. Now, when
returns from 1 to 20, $var matches $hex. (Like 0x0001 .... 0x0014)

But when $entry is 0, $var becomes
. But I want it to be
. Currently, I am checking if that is
, I am changing it through a if loop. Please let me know if that is possible in sprintf itself.


According to the documentation for sprintf:

# prefix non-zero hexadecimal with "0x" or "0X"

Note that it says non-zero, so only non-zero values will be prefixed by 0x.

A simple fix is to add the prefix manually:

sprintf "0x%04x", $entry;