Comparing Hex Numbers in Strings.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • roniz5
    New Member
    • Feb 2007
    • 5

    Comparing Hex Numbers in Strings.

    Hi,

    I'm trying to sort a file according to a hexa value that appears in every line.

    Since I don't remember how to convert hex2int, I tried and noticed that this works:

    $val1= "0x0A"; $val2=10;

    if ($val1 == $val2) {print "OK";}



    So, I tried to use just a simple compare as the above (hexa against integer, with no conversions) in my script that sorts the file.

    But here I encountered this problem: $1 does not get the whole meaning of the string in brackets. What do I mean? look at the next lines, they should have worked but they don't:

    $val1=10; $val2="this line contains the value 0x0A";

    if ($val2 =~ /the value (0x\w)/)

    {if ($val1 == $1) {print "OK";}}



    This did not work!!

    Just to show that the problem is with the $1 interpretation, I printed out to the screen the content of $1 and it printed out correctly: 0x0A.

    Can someone explain this to me?



    Thanks

    Roni

    roniz5@yahoo.co m
  • KevinADC
    Recognized Expert Specialist
    • Jan 2007
    • 4092

    #2
    Code:
    my $val1 = 10;
    my $val2 = "this line contains the value 0x0A";
    
    if ($val2 =~ /the value (0x\w+)/){
       if ($val1 == oct($1)) {
          print "OK";
       }
    }
    Last edited by KevinADC; Feb 19 '07, 07:21 AM. Reason: added code tags

    Comment

    • KevinADC
      Recognized Expert Specialist
      • Jan 2007
      • 4092

      #3
      see:



      and:

      Comment

      • docsnyder
        New Member
        • Dec 2006
        • 88

        #4
        More precisely and therefore robust would be:
        Code:
        /the value (0x[\da-f]+)/i
        Greetz, Doc

        Comment

        • roniz5
          New Member
          • Feb 2007
          • 5

          #5
          Originally posted by KevinADC
          Code:
          my $val1 = 10;
          my $val2 = "this line contains the value 0x0A";
          
          if ($val2 =~ /the value (0x\w+)/){
             if ($val1 == oct($1)) {
                print "OK";
             }
          }
          --------------------------------------------------

          Thanks a lot, it works!
          And thank you also for the link to the relevant info.

          Roni

          Comment

          • roniz5
            New Member
            • Feb 2007
            • 5

            #6
            Originally posted by docsnyder
            More precisely and therefore robust would be:
            Code:
            /the value (0x[\da-f]+)/i
            Greetz, Doc
            Thanks you very much, I will use the /i - you saved me a future bug...

            Roni

            Comment

            Working...