Reading QR Codes from Perl


Intrigued by reading QR codes from Perl? Barcode::ZBar can be your friend!

I can’t really tell you why I care about reading QR codes at all - I’ve never really needed to do that programmatically. But the possibility to do this in Perl always intrigued me. Do you share the same curiosity? Let’s be Barcode::ZBar’s guests together, then!

Installing dependencies

If you want to give it a try before you buy, I suggest to Try with Docker! Just make sure to install both libzbar-dev and perlmagick.

After this, you have to install Barcode::ZBar somewhere. You know what I think about Installing Perl Modules so I will not repeat that here. Spoiler: use carton.

Getting a sample QR code

There are a lot of QR code generators around, I chose QR Code Generator because it allows saving in a PNG image. You can generate your own or just use the one below (which you can download from here):


The example program

I took the example program from CPAN, as of release 0.04 of Barcode::ZBar:

use warnings;
use strict;
require Image::Magick;
require Barcode::ZBar;
$ARGV[0] || die;
# create a reader
my $scanner = Barcode::ZBar::ImageScanner->new();
# configure the reader
# obtain image data
my $magick = Image::Magick->new();
$magick->Read($ARGV[0]) && die;
my $raw = $magick->ImageToBlob(magick => 'GRAY', depth => 8);
# wrap image data
my $image = Barcode::ZBar::Image->new();
$image->set_size($magick->Get(qw(columns rows)));
# scan the image for barcodes
my $n = $scanner->scan_image($image);
# extract results
foreach my $symbol ($image->get_symbols()) {
    # do something useful with results
    print('decoded ' . $symbol->get_type() .
          ' symbol "' . $symbol->get_data() . "\"\n");
# clean up

Running it

It turns out that running it actually works:

root@769f7f634955:/mnt# perl -I local/lib/perl5 2020-01-japh.png 
decoded QR-Code symbol "Just Another Perl Hacker"

Amazing! To say that QR codes aren’t even mentiones in the Barcode::ZBar documentation 😅


So… it seems that it’s not difficult to use Barcode::ZBar after all. Why don’t you give it a try then?

Comments? Octodon, Twitter, GitHub, Reddit, or drop me a line!