Connecting Tech Pros Worldwide Help | Site Map

Comparing Hex Numbers in Strings.

Newbie
 
Join Date: Feb 2007
Posts: 5
#1: Feb 19 '07
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.com
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#2: Feb 19 '07

re: Comparing Hex Numbers in Strings.


Expand|Select|Wrap|Line Numbers
  1. my $val1 = 10;
  2. my $val2 = "this line contains the value 0x0A";
  3.  
  4. if ($val2 =~ /the value (0x\w+)/){
  5.    if ($val1 == oct($1)) {
  6.       print "OK";
  7.    }
  8. }
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#3: Feb 19 '07

re: Comparing Hex Numbers in Strings.


see:

http://perldoc.perl.org/functions/hex.html

and:

http://perldoc.perl.org/functions/oct.html
docsnyder's Avatar
Member
 
Join Date: Dec 2006
Location: Darmstadt
Posts: 88
#4: Feb 19 '07

re: Comparing Hex Numbers in Strings.


More precisely and therefore robust would be:
Expand|Select|Wrap|Line Numbers
  1. /the value (0x[\da-f]+)/i
Greetz, Doc
Newbie
 
Join Date: Feb 2007
Posts: 5
#5: Feb 19 '07

re: Comparing Hex Numbers in Strings.


Quote:

Originally Posted by KevinADC

Expand|Select|Wrap|Line Numbers
  1. my $val1 = 10;
  2. my $val2 = "this line contains the value 0x0A";
  3.  
  4. if ($val2 =~ /the value (0x\w+)/){
  5.    if ($val1 == oct($1)) {
  6.       print "OK";
  7.    }
  8. }

--------------------------------------------------

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

Roni
Newbie
 
Join Date: Feb 2007
Posts: 5
#6: Feb 19 '07

re: Comparing Hex Numbers in Strings.


Quote:

Originally Posted by docsnyder

More precisely and therefore robust would be:

Expand|Select|Wrap|Line Numbers
  1. /the value (0x[\da-f]+)/i
Greetz, Doc

Thanks you very much, I will use the /i - you saved me a future bug...

Roni
Reply