2

I have a variable, $count, which will take a decimal value from the command line, and I have a piece of code which generates files with name filename001 filename002 ....filename00a,filename00b etc. It appends a hexadecimal number(without 0x) to filename for every new file it generates.

I use the variable $count to keep track of the number that is appended to filename. I want to pull out lines containing a particular text Result: from the generated file (filename00b filename00a, etc.). For this purpose I use the grep tool in the following way:

`grep "Result:" path to the file/filename0*$count`

This works fine till I reach the 10th file when 10 becomes a in hexadecimal, but $count in the grep command is simplified to 10, so grep is not able to find the file. I tried using hex($count), but it does not seem to work. It required that $count variable can be incremented or decremented, and it still holds the hex value. Is there a way to do this?

1 Answer 1

8

The hex function in perl interprets its argument as a hex string and returns the corresponding integer value, for example:

print hex '0xAf'; # prints '175'
print hex 'aF';   # same

This from the definition of hex in perldoc -f hex.

It seem you want to do the opposite, convert your decimal number to a hex representation. You can do that with printf for example:

printf("%03x", 175); # prints '0af'
printf("%03x", 0xAf); # same

If you want to save the value in a variable, use sprintf instead of printf, it returns the string instead of printing it.

Sign up to request clarification or add additional context in comments.

4 Comments

:I tried with sprintf , $count now has hexadecimal equivalent of the decimal number ,but when i try to increment it ,i get a message saying that the content in variable is a string . I would be nice if there is a method use hex numbers directly in variable .
An integer is an integer, whether you look at it in decimal form, hexadecimal or octal is a matter of formatting. Keep $count as a number, increment or decrement or manipulate it as you like, and when you want it formatted as hexadecimal, use sprintf. If you want the reverse, and get a number back from the hexadecimal string then use the hex function of perl.
@Gautam You should understand the difference between a number (as a value) and its representation with symbols (usually called as digits). The count of x-es here 'xxxxx' is 5 in decimal, and V in roman numeral system and 101 in binary.. when you increment (add one) to the five x-es, you get 'xxxxxx' what is 6 or VI or 110 - based on how you want represent it.
@janos you are right I will have to do it the way you have suggested ,thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.