SibiCoder SibiCoder - 6 months ago 8
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
function
returns from 1 to 20, $var matches $hex. (Like 0x0001 .... 0x0014)

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

Answer

According to the documentation for sprintf:

flags
# 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;