Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am having a problem with passing a hex number argument to a function that takes string argument. I do not want to change those function to expect hex number because then I'll have to make tons of changes. To be more specific:
# my $num = 0x100; my $chr = string of $num; # not sure what this should be call_f2($chr); sub call_f2{ my $str = shift; &f2($str); } sub f2 { my $str = shift; print ($str); } # I want to print 100, is it possible?

Replies are listed 'Best First'.
Re: passing hex argument as string
by pg (Canon) on Nov 04, 2003 at 02:43 UTC

    One way is to use sprintf:

    use strict; use warnings; my $bar = 0x100; print foo(sprintf("%x",$bar)); sub foo { return shift() . "abc"; }

    You can check out perlfunc for details of this function.

Re: passing hex argument as string
by batkins (Chaplain) on Nov 04, 2003 at 02:44 UTC
    Well, I'm not sure I'm getting what you're getting at. First of all, the call_f2 sub is entirely superfluous. Now you're comment says that you're trying to print 100. I'm not sure what that means. If you want to print $num in base-10, you should be able to just print it out. If you want to print it in hex (base-16), try:
    printf "%x", $chr;
    Are you sure it was a book? Are you sure it wasn't.....nothing?
      yes I am familiar with printf function. But I can not do that. Beccause the function that takes $chr is *FIXED*, and I can not change it. So what I want is a function that: # takes a hex number 0xff # returns string "ff" and NOT 255
        That's what
        sprintf("%x", $hexnum)
        does. If $hexnum is 0xdeadbeef, the sprintf will return "deadbeef". (Use %X instead of %x if you want "DEADBEEF".)

        (updated to correctly say sprintf instead of printf)

Re: passing hex argument as string
by TomDLux (Vicar) on Nov 04, 2003 at 03:25 UTC

    The hex number exists only on the right hand side of line 1; the value stored in $num is 0...0100000000, popularly known as 256.

    If f2 doesn't do any calculations with the argument, only print it out, you might be able to pass in the number as a hex string:

    f2( sprintf "0x%0x", $num );

    --
    TTTATCGGTCGTTATATAGATGTTTGCA

Re: passing hex argument as string
by ysth (Canon) on Nov 04, 2003 at 11:44 UTC
    The simple answer is to create the string with sprintf "%x". There's more information about controlling the hexadecimal formating in the Categorized Q&A How do I convert from decimal to hexidecimal?.

    (updated to correct my hexi->hexa but leave the Q link wrong)

    That's the end of the practical answer. Flight of fancy follows...