You are the 2646th visitor to this page since May 30, 2001.

Introduction

Tom and Nathan have written an excellent "Perl Cookbook" holding many solutions to common problems. It has solved many problems for me the last years, but... I very often run into problems for which there is no solution in the cookbook. I decided to organize my own engineered solutions into a web Perl cookbook. This page is not to be seen as an alternative to Tom's and Nathan's book, but rather as a complement.

This is to be considered work-in-progress, which is why there might not be to many entries here initially.



Recipes

Converting a Hex String to Values

Problem

You want to convert a string of hexadecimal characters to a list of their byte-values.

Solution

Use a combination of pack and unpack to (1) pack the hex string into a binary structure and then (2) unpack the binary structure into a list of unsigned char values:
$hex_string = "000102031F";
$STRING = pack("H*", $hex_string);      # (1)
@VALUE = unpack("C*", $STRING);         # (2)

Discussion

The problem occured when I was writing a program to read and parse Motorola S-records in a file. The data part of each S-record consists of a hex-string which is then to be interpreted as data bytes.
© 1996 Matz Kindahl <matkin@docs.uu.se>
Last modified: Wed May 30 10:31:29 2001