Perl hex Function



This short Perl hex Tutorial will show you how to use this function in various contexts. I’ll point out through several snippet code examples what I consider more important in order to highlight the topic.

Two syntax forms are available for Perl hex function:

hex EXPR 
hex

This function:
  • has as argument a hexadecimal string (or an expression which after evaluation will return a hex string)
  • will return the decimal corresponding value

Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!

For instance, see below how you can call it:

print hex "0x4E8", "\n";  # or
print hex "4e8", "\n";

As you see above, a hexadecimal string begins with the characters 0x (which could be omitted in a hex context) and is case insensitive. Please note that here the hexadecimal strings represent integers and not any other kind of data.

In the second syntax form of Perl hex function, the expression argument is omitted and the function will use by default as argument the hexadecimal value stored in the special variable $_.

Next, I’ll give you some examples about how you can use and manipulate Perl hex function and some related considerations.



Convert a decimal number into a hexadecimal one


If Perl hex function converts a hexadecimal value into decimal, maybe you could have expected to find a similar function which will do the reverse, i.e. convert a decimal number into a hexadecimal one. Well, it’s not just like that. We can do this very simply by using the Perl sprintf function formatting, as in the next example:

# initialize a scalar variable with an integer value
my $dec = 1211;

print "Hexadecimal number: ", uc(sprintf("%x\n", $dec)), "\n";
# displays 4BB

We used the %x to format the decimal scalar value into hexadecimal and we converted the result in uppercase, but we could let it in lowercase too, as the sprintf function returns it by default.

This is a direct conversion method when we need to use a reverse function for Perl hex function. If you want to write some code and emulate the algorithm used by sprintf formatting, here is an example:

# initialize a scalar with an integer value
my $dec = 1211;

# call the subroutine
my $hex = DecToNumBase($dec, 16);
print "Hexadecimal number: $hex\n";
# displays 4BB

# define the subroutine
sub DecToNumBase
{
  my $decNumber = $_[0];
  my $numBase = $_[1];
  my $numNumber = '';

  while($decNumber ne 'end') 
  {
    # divide the decimal number by $numBase and 
    # store the remainder (modulus function) in 
    # the temporary variable $temp
    my $temp = $decNumber % $numBase;
    if($temp > 9) 
    {
      $temp = chr($temp + 55);
    }
    $numNumber = $temp . $numNumber;
    $decNumber = int($decNumber / $numBase);
    if($decNumber < $numBase) 
    {
      if($decNumber > 9) 
      {
        $decNumber = chr($decNumber + 55);
      }
      $numNumber = $decNumber . $numNumber;
      $decNumber = 'end'; 
    } 
  }
  return $numNumber;
}

In the example above we defined and called the DecToNumBase subroutine which is meant to convert a decimal value into a number in another numeration base. This subroutine has as input two arguments:

  • the decimal value to be converted
  • the numeration base
The while loop will stop when after dividing the decimal number by the numeration base we will get as result a number less than the numeration base. Please note the using of Perl chr function and the concatenation operator '.'. We called this function to convert a decimal number into a hexadecimal one. You can use this function either to convert a decimal number into octal, binary or whatever. We didn't use Perl hex function in the above subroutine but we consider that the code is useful to see how to do things in similar situations.

Convert a scalar string to hex


The following snippet code will show you how to convert a scalar string into its hexadecimal format. It takes any character within the string and returns its hexadecimal code:

my $myString="This text is only for test reason 123 [{@!}}|";

my @myArray=unpack('C*', $myString);
my $myStringHex = '';

foreach my $c (@myArray) {
  $myStringHex .= "\%" . sprintf ("%lx", $c);
}

print "$myStringHex\n";

The Perl unpack function uses the C parameter to convert each character in byte. Perl sprintf function is used to format the byte code in hex. To get all the converted characters in a string, the concatenation "." operator is used.

Encode and decode an URL


An URL (or Uniform Resource Locator) is a particular type of URI (which stands for Uniform Resource Identifier). By URI we mean a specific string used to identify an abstract or physical resource.

Everyone who is searching through Internet knows about URL (or more precisely, he should know). Let’s say that through URL we understand an internet address of a page we are searching for, it could be the address of this page too (URL=http://www.misc-perl-info.com/perl-hex.html).

There are some restrictions of using the characters in an URL. Through the characters allowed there are the alphanumerical characters [0-9a-zA-Z], some punctuation symbols $-_.!*'(), and some reserved characters used for other purposes.

All the other characters must be encoded, because they could be misunderstood if they are found within an URL. To encode a character means to replace it by the symbol % followed by its two-digit hexadecimal code. For instance, the space character which has the hexadecimal code 20, will be represented as %20.

The simplest mode to encode or decode an URL is by using the Perl URI::Escape module, which exports the following functions:

  • uri_escape – which replaces (encodes) all unsafe characters within a URL string with two hexadecimal digits preceded by the % symbol
  • uri_unescape – which unencodes all the characters within an URL, i.e replaces any occurrence of % followed by two hexadecimal digits into their corresponding character (in other words converts an encoded URL to its normal representation)
The next example will show you how to do this:

use URI::Escape;
 
# Encode URL
my $url = "http://www.google.com/search?q=book";

my $encodedURL = uri_escape($url);
 
print "Encoded URL: $encodedURL\n\n";

# Decode URL

$encodedURL = 
  "http://%77%77%77%2e%79%61%68%6f%6f%2e%63%6f%6d";

my $decodedURL = uri_unescape($encodedURL);
print  "Decoded URL: $decodedURL\n";

The uri_unescape function is very useful if you will receive an invitation to click on a link with escaped characters that looks like "http://%77%77%77%2e%79%61%68%6f%6f%2e%63%6f%6d" and it will be nice to know where you will go if you click on it. Decode it like in the example above and than decide what you will do. If you want to see what URL represents the above address, just copy the string above (neglect the quotes) in your browser address bar and see where it is pointing out (in my 3.0.6 FireFox it works).

We hope that these considerations help you see how to use Perl hex function in your scripts. If you have any idea to add some more useful examples about Perl hex function, feel free to tell me by using my contact form.

If you want to download the Perl hex script with all the above examples included, please click here: Script download

A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!


Check these how-to tutorial eBooks (PDF format):


Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        chomp
        chop
        chr
        crypt
        defined
        delete
        each
        exists
        grep
        hex (more)
        index
        join
        keys
        lc
        lcfirst
        length
        map
        oct
        ord
        pack
        pop
        push
        q
        qq
        qw
        reverse
        rindex
        scalar
        shift
        sort
        splice
        split
        sprintf
        substr
        tr
        uc
        ucfirst
        undef
        unpack
        unshift
        values

return from Perl hex function to Perl Basics



Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!