Create your blog and photo album with postbit
Create your blog and photo album

Create new post


Upload a picture:
Tags (keywords separated by comma)

Save Cancel
perl:   Followers: 2 ; Following: 2

Explore perl's photo albums:
Photos from posts (2)
Perl images (1)

How to create Excel files with Perl

To create .xls files using Perl, you'll need to use the CPAN module:

use Excel::Writer::XLSX;
It's better than the previous "Spreadsheet::WriteExcel" because:
1. It does not diplay error when opening perl generated .xls using Microsoft Excel Starter 2010:
"There are worksheets in this workbook with frozen panes. You may not be able to see all the data.
To ensure you can see al the data, request a version of this workbook with no frozen panes."

2. Files with .xlsx extension are usually smaller than previous .xls version.

3. XLSX files can have more lines than XLS files.


If you will use Excel to open Perl generated files, it may be better to use XLSX than CSV because some CSV files will open in a single column (instead of multiple columns). Even using tab separated values or comma, Excel may open .csv extension files with all fields (columns) in one column only.


Simple example of writing .xlsx file using Perl:

# Description: Create Excel file with Perl
use strict;
use Excel::Writer::XLSX;
# Create new Excel workbook
my $outfile = '/tmp/tmp.xlsx';
print "Writing .xlsx to $outfile\n";
my $workbook = Excel::Writer::XLSX->new( $outfile );
# Add a worksheet (tab)
my $worksheet = $workbook->add_worksheet();
# Add format
my $format = $workbook->add_format();
$format->set_align( 'center' );
$format->set_color( 'blue' );
my $col = 0;
my $row = 0;
# Write a formatted string
$worksheet->write( $row, $col, 'Excel Formatted string', $format );
# Write and unformatted string
$worksheet->write( $row, $col, 'Simple string' );
# Write a number using A1 notation
$worksheet->write( 'A3', 1000 );
# Write formula
$worksheet->write( 'A4', '=A3+PI()' );
### END ###

Post by perl (2014-09-17 17:25)

Post your comment:

Name: Email: Site:

Using arrows to access terminal history with Perl

It's great to use up-arrow to access past history commands when using a terminal in Perl.

But if you are trying to use arrows in a perl terminal that reads <STDIN> (e.g. CPAN terminal) you may get this error (display control characters instead of correct arrow function):
^[[A (when pressing up arrow)
^[[B (when pressing down arrow)
^[[C (when pressing right arrow)
^[[D (when pressing left arrow)

You may also get those errors:
Terminal does not support GetHistory
Terminal does not support AddHistory

So you need to install (using CPAN) to fix the backhistory arrow error:


install Term::ReadLine
install Term::ReadLine::Perl
install Term::ReadLine::Gnu

If need also install Term::ReadKey if you "use Term::Readline" and get the following error:
Can't ioctl TIOCGETP: Invalid argument'

If you get this error: "Could not find neither libtermcap.a, libncurses.a, or libcurses.", then you need to install readline-devel (e.g. cygwin module or yum install) in your server:

yum install readline-devel
This will also install ncurses-devel.

Then try again to use CPAN to install Term::ReadLine::Gnu

If you use Ubuntu, then install libterm-readline-gnu-perl with the command:
sudo apt-get install libterm-readline-gnu-perl

Term::ReadLine example:

This is a simple perl script that uses Term::ReadLine to create a simple terminal for tests, that works with up-arrow to view past history of commands:


use Term::ReadLine;
my $term = Term::ReadLine->new('My Perl Terminal');
while (1) {
  my $cmd = $term->readline("prompt> ");
  print "You wrote '$cmd'\n";
If Term::ReadLine is working only for root account, then check if the module is wrongly installed in a @INC path that only root has access. Example:
Then you need to move to other path, accessible to other users.
I had to comment the following lines from root's .bashrc ao avoid CPAN installing modules under /root/perl5/lib directory:
#export PERL_MB_OPT="--install_base /root/perl5";
#export PERL_MM_OPT="INSTALL_BASE=/root/perl5";
#export PERL5LIB="/root/perl5/lib/perl5:$PERL5LIB";
#export PATH="/root/perl5/bin:$PATH";
### END ###

Post by perl (2014-06-04 20:41)

Post your comment:

Name: Email: Site:

How to list all installed Perl modules

I had to learn how to list installed perl modules because I had to reinstall some modules because of this Perl_Istack_sp_ptr error:
/usr/bin/perl: symbol lookup error: /usr/local/lib/perl5/auto/Time/HiRes/ undefined symbol: Perl_Istack_sp_ptr

I had to uninstall perl and reinstall perl again because I was getting the error after upgrading my Amazon EC2 Instance (after aws server upgrade using command "sudo yum -y update"

Error when trying to run some perl scripts and CPAN:
"undefined symbol: Perl_Istack_sp_ptr".

To solve this Perl_Istack_sp_ptr error I had to remove the perl module directory. I copied to a temporary location before deleting:
mv /usr/local/lib64/perl5 /tmp

If you are using 32 bit server, then the command is:
mv /usr/local/lib/perl5/ /tmp

Then I removed Perl and installed again. You may not need to remove Perl. Only removing the perl modules directory and reinstalling Time::HiRes using CPAN was enough to make perl work again:
install Time::HiRes (this will create again the directory "/usr/local/lib/perl5/")

Since I had many custom CPAN modules installed, I listed them and installed the perl modules again using yum (instead of using CPAN).

Yum command to list of all Perl modules that are installed in the server:

yum list | grep perl | cut -d\  -f1 > installed-perl-modules.txt

If you need to remove current perl using yum the command is:
yum remove perl

If you need to remove perl and re-reinstall all modules using yum, you can use the command:

yum install $( cat installed-perl-modules.txt )

Example of some installed perl modules from this list:

The extension can be ".i686" (if you are using 32bit server architecture) instead of ".x86_64" (if using 64 bit)
You can omit the extension (x86_64 or i686) when installing using yum.
yum install perl-Time-HiRes


Post by perl (2014-03-29 14:24)

Post your comment:

Name: Email: Site:

How to compile a PERL script to EXE

Use PERL2EXE to compile a perl script to Windows or Linux executable. You don't need to have installed PERL to use PERL2EXE, since it comes with the perl libraries needed to create the exe. But if your script contains modules (uses .pm) then you need to have Perl installed the perl2exe can find the pm libraries to compile them into the exe file.

Just type:

perl2exe (

And it will generate "your-perl-script.exe", a stand-alone executable. The same exe file can be executed under Windows and also cygwin.

The size of the executable compiled script will be about 485 kb (for a simple hello world script), since it will include the perl engine and DLL needed to run perl.

Your source code will be protected and you can distribute the exe program to be run in any Windows machine (no need to install Perl). Probably the source code will be cryptographed inside the exe, since perl2exe uses the following commands:
load Crypt::RSA::Key
load Crypt::OpenPGP::CFB

You can download perl2exe here:
There's a free working version that can be downloaded (the paid version to generate .exe for Windows is $49).
It was also called "exe2perl" but now is "PERL2EXE". It doesn't need to be installed, just unzip under any directory. The files of PERL2EXE are:


The problem with the free version is that it will display the alert message:

This exe file was created with the evaluation version of Perl2Exe.
For more information visit
(The full version does not display this message with a 2 second delay.)

Post by perl (2013-10-23 15:33)

Post your comment:

Name: Email: Site:

How to identify if Perl script is running under cygwin

How to check in which operating system the Perl script is running

Use the SERVER OSNAME ( $^O ) to identify the operating system where the PERL script is running. This is needed when your perl script must execute or run different commands under distinct operating systems.

When running perl under CYGWIN, the $^O variable will contain "cygwin" value.

Perl code to identify the current operating system:

if ($^O eq 'cygwin') {
  print "This perl script is running under cygwin\n";
} elsif ($^O eq 'MSWin32') {
  print "This perl script is running under ms windows\n";
} elsif ($^O eq 'linux') {
  print "This perl script is running under linux\n";

If you are using bash, you can check the $(uname) variable. In my system this is what is displayed:

> echo $(uname)
Beware the $ENV{OS} environment variable, that contains "Windows_NT" even when running under cygwin.
To test if the script is running as CGI, check the $ENV{GATEWAY_INTERFACE} that only have a value if running under a web server. For example in my web server (Apache), it contains "CGI/1.1" when running as a cgi-bin or mod_perl.

Post by perl (2013-10-23 14:17)

Post your comment:

Name: Email: Site:

How to identify a language using PERL

To identify language of a text (e.g. language of a webpage), it is possible Chromium’s CLD (Compact Language Detection) and it's Perl Interface to the Chrome language detection library CPAN module Lingua::Identify::CLD

There is an other module to identify language, that's Lingua::Identify, but unfortunately it does not identify many languages and is missing identification of some important languages like Japanese and Chinese.

In case of identification of web pages languages, it is also possible to use the top level domain extension (optional 'tld' parameter) as a hint to identify the correct page language. Usage example, using TLD hint:

use Lingua::Identify::CLD;
my $cld = Lingua::Identify::CLD->new();

my $lang = $cld->identify("My Text", tld => 'uk'); # ENGLISH

List of supported languages and language codes:

Pre-requisites to install: If you get the error "cc: error trying to exec 'cc1plus': execvp: No such file or directory", then install "g++" and the installation will run correctly.

I was not able to install Lingua::Identify::CLD under windows cygwin, because I got this error:

cld-src/base/build_config.h:121:2: error: #error Please add support for your compiler in build/build_config.h

error building cld-src/encodings/compact_lang_det/cldutil.o from 'cld-src/encodings/compact_lang_det/' at /usr/lib/perl5/5.14/ExtUtils/CBuilder/ line 175, <DATA> line 226.

Post by perl (2013-09-03 20:46)

Post your comment:

Name: Email: Site:

Perl pack w (compressing integer numbers)

pack w is a perl command used to compress an integer number using few bytes.
It uses 50% less space (bytes) than usual integer number. It compresses integer by using about half byte per digit.

$int = 1234567890; # length of $int is 10
$int_compressed = pack('w', 1234567890); # now the length of $int_compressed is just 5

# Recovering the original integer value with unpack:
$int_orig = unpack('w', $int_compressed); # 1234567890

The documentation (perldoc -f pack) says that "w" pack parameter means "BER compressed integer", where BER means Basic Encoding Rules.

pack w can only be used to compress positive integers (zero is also valid). But if you try to compress a negative integer number, e.g. $x = pack('w', -5), the error will be: "Cannot compress negative numbers in pack"

Let's see the binary content inside the packed variable, saving the compressed integer in $x variable and then using unpack as binary to convert the bytes to binary representation:

$x = pack('w', 8);
print unpack('B*', $x); # 00001000 (it's just a single byte representing the number 8 in binary)

$x = pack('w', 1024);
print unpack('B*', $x); # 1000100000000000 (now it has the size of 2 bytes. It's not just the conversion of '1024' to binary, it's the compressed representation of 1024 in the pack w format)

Compressing an array of integers:

More information from "man perlpacktut", showing that pack w* can store an array of integers in a single variable ($berbuf):

my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 );
A hex dump of $berbuf, with spaces inserted at the right places, shows 01 8100 8101 81807F. Since the last byte is always less than 128, "unpack" knows where to stop.
To restore the original array of integers:
@array = unpack('w*', $nerbuf);
Now @array contains the original compressed array of integers (1, 128, 129, 16511);

Post by perl (2013-09-03 20:26)

Post your comment:

Name: Email: Site:

How to serialize a PERL array to use with memcached

It is possible to use JSON module serialize PERL objects to store in memcached.


use Cache::Memcached;
use JSON;
my $memcached = new Cache::Memcached {
    'servers' => [''],
    'debug' => 0,
    'compress_threshold' => 10_000,
my @array = ({'a'=>1}, 'x'); # Add 2 elements to array
my $serialized = JSON::to_json(\@array);


# Store serialized array to cache
$memcached->set("var_name", $serialized);

# Read serialized JSON value string from memcached
my $serialized_from_cache = $memcached->get("var_name");
my $ref = JSON::from_json($serialized_from_cache);

print $ref->[0]->{'a'}; # Will print '1'
print $ref->[1]; # Will print 'x'

Post by perl (2013-04-03 14:54)

Post your comment:

Name: Email: Site:

How to read a compressed file with Perl

How to read a zip file using Perl (also reads .gz and .bz2)

This script tests if file is compressed with gzip (.gz), zip or bzip2 (.bz2) and reads the file using the appropriate file decompressor (/bin/gzip or /usr/bin/unzip or /usr/bin/bzip2) to uncompress the file and read its content with Perl open pipe command.

gzipped compressed file) and uses gzip -cd to read the file. That is like gunzip because -d is decompress and -c is write output to standard output.

If the extension is not .gz or .zip or .bz2, then this script will open the file as an uncompressed file.

my $uncompress;

if ($filename =~ /\.zip$/i) {
  $uncompress = '/usr/bin/unzip -p'; # -p = pipe output to STDOUT
} elsif ($filename =~ /\.gz$/i) {
  $uncompress = '/bin/gzip -cd'; # -d = decompress; -c = write to STDOUT
} elsif ($filename =~ /\.bz2$/i) {
  $uncompress = '/usr/bin/bzip2 -cd';

if ($uncompress) {
  open (FILE, "$uncompress $filename|")
  || die("ERROR: $uncompress can not read file ($filename): $!\n");
} else {
  open (FILE, $filename)
  || die("ERROR: Can not read file ($filename): $!\n");

while (my $line = <FILE>) {
  print $line;

close FILE;


Post by perl (2012-11-18 00:22)

Post your comment:

Name: Email: Site:

How to create a temporary file with Perl

You don't have to use File::Temp module to open temporary anonymous files with Perl.

To create a temporary file using perl, you can use "open" with the special case of three-argument form with a read/write mode ("+>") and the third argument being "undef". This will open a filehandle to an anonymous temporary file:

    open(TMP, "+>", undef) or die ...

When your write is finished, you can use "seek (TMP, 0, 0)" to go to the beginnig of the file and start reading it. 

Example of how to create a temporary file with Perl: 


open(TMP, "+>", undef) or die "Can not open temporary file";

print TMP "Content of the anonymous file\n";

# Move to the beginning of file

# Read contents of the anonymous file
while (my $line = ) {
  print "Read line: $line";

my $bytes = (stat(TMP))[7];
print "File size: $bytes bytes\n";

# Delete the temporary file
close TMP;

This is a full working example of how to write to an anonymous file and read from it, using Perl. The expected output of this Perl script above is:

Read line: Content of the anonymous file
File size: 30 bytes

Perl will not give the filename, since it's temporary. But you can get its inode number using "stat". Using strace you can see where Perl creates the temporary file and it's unique filename (something random generated filename like "/tmp/PerlIO_fS1ehi").
This feature works since Perl 5.8.0 version.

Post by perl (2012-11-09 15:37)

Post your comment:

Name: Email: Site:

  << PREVIOUS PAGE Page 2 of 3 NEXT PAGE >>

| Explore users | New posts | Create your blog | Create your photo album |
| About Postbit | Our blog | Terms of use | Contact Postbit |

Copyright © 2018 -