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

Hi monks, i have a question concerning binary identifiers coming from sql server. I'm using DBI to retrieve rows that contain a binary data type, and then i use unpack.
# ... DBI stuff ... grab row with binary datatype $parent_hex = '0x0' . unpack("H*",$row->{parentid});
I want to determine whether $parent_hex is zero but for some reason the below comparison doesn't work
if ( !$parent_hex ) { #do something } else { #do something different }
how can I successfully compare $parent_hex to 0x000000000? thanks, Michael

Replies are listed 'Best First'.
Re: binary ids
by Paladin (Vicar) on Feb 10, 2003 at 17:26 UTC
    You could do something like the following:
    if ( hex($parent_hex) != 0) { # $parent_hex isn't 0 }
    hex will convert a hex string into it's numerical value. Then compare that with 0.

      In fact all you need is if( $parent_hex == 0 ) { blah } as the numeric comparison forces perl to convert the sv to a number and 0x00000 is correctly interpretted as 0 automagically. The problem with the if (! $parent_hex) {} example given is that without forcing numeric context perl sees the sting '0x0' which is not a null string '' and thus not false in this context.

      cheers

      tachyon

      s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

        This is misleadingly incorrect. You assume that just because the perl compiler will read a plain 0x0005 as the numeric value 5 that the same thing in a scalar behaves the same way. In this case strings with leading numbers are evaluated in numeric context as the value of the leading number. In this case this means that $var = "0x0005"; $var == 5 is false - in fact, $var == 0 because $var begins with the string "0".

        The correct answer is to use the hex() function. You'd have to resort to using eval to get your idea to work (which re-invokes the compiler which has its own rules...).


        Seeking Green geeks in Minnesota

Re: binary ids
by BrowserUk (Patriarch) on Feb 10, 2003 at 18:20 UTC

    As the only value of $row->{parentid} that could produce a hex value of 0x00000000 is a string of 4 ascii 0 (zero) bytes, then you could do

    if ( $row->{parentid} =~ /^\0{4}$/ ) { # do something; } else { $parent_hex = '0x0' . unpack 'H*', $row->{parentid}; # do something else }

    Examine what is said, not who speaks.

    The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.