How to get MD5 hash in Perl

Task. In Perl the code is variable. You need to calculate the MD5 hash from the value of this variable.

The decision

The solution is to use Perl library Digest::MD5. Library Digest::MD5 comes with Perl, so if you have Perl, this library is available to additionally install nothing.

Get MD5 hash using this code:

▶ Run
#!/usr/bin/perl

use Digest::MD5 qw(md5_hex);

my $var = 123;

my $md5_hash = md5_hex($var);

print $md5_hash;

This program displays the string '202cb962ac59075b964b07152d234b70'.

  • use Digest::MD5 qw(md5_hex); — we connect Perl library and say that from this library we need a function md5_hex
  • my $var = 123; — created a variable and put the value 123
  • my $md5_hash = md5_hex($var); — using functions md5_hex we calculated the MD5 hash from the value of a variable $var and put the result in a variable $md5_hash
  • print $md5_hash; — brought the value of the variable $md5_hash on the screen

If the library does not indicate that we need a function md5_hex, and just write use Digest::MD5;, when execution of the program will be error:

Undefined subroutine &main::md5_hex called at a.pl line 7.

The format of the return value of a function md5_hex

Function md5_hex always returns a string. This string is always exactly 32 characters. This line can be the numbers from 0 to 9 and Latin letters in lower case from 'a' to 'f'. Other symbols in this row can not be.

Function md5_hex returns the MD5 as a string which contains a number in hexadecimal notation.

Other articles

Comments