31 Dec 2010

Perl New year wish

perl -le 'print pack "H*","4861707079204e657720596561722032303131"'

22 Dec 2010

Download youtube videos - Perl

Perl one-liner to download youtube videos

perl -MWWW::Mechanize -e '$m = WWW::Mechanize->new; $_=shift; ($i) = /v=(.+)/; s/%(..)/chr(hex($1))/ge for (($u) = $m->get($_)->content =~ /l_map": .+(?:%2C)?5%7C(.+?)"/); $m->get($u, ":content_file" => "$i.flv")'

Use it as following:

$ perl ... http://www.youtube.com/watch?v=ID

It will save the video to a file named "ID.flv".

It was written by Peteris Krumins (peter@catonmat.net).
His blog is at http://www.catonmat.net -- good coders code, great reuse.


Framework for getting process information

Find it at: cpan


This modules gets the process information

Who should use it?

Very useful for sysadmins

Good features:

Good to extract process related information and it is very fast

What are the drawbacks or problems?

Not working on some Linux flavors
There are 13 open bugs

Example code:

#!/usr/bin/perl -w

use strict;

print join("\n", &memusage), "\n";
exit 0;

# memusage subroutine
# usage: memusage [processid]
# this subroutine takes only one parameter, the process id for
# which memory usage information is to be returned. If
# undefined, the current process id is assumed.
# Returns array of two values, raw process memory size and
# percentage memory utilisation, in this order. Returns
# undefined if these values cannot be determined.

sub memusage {
use Proc::ProcessTable;
my @results;
my $pid = (defined($_[0])) ? $_[0] : $$;
my $proc = Proc::ProcessTable->new;
my %fields = map { $_ => 1 } $proc->fields;
return undef unless exists $fields{'pid'};
foreach (@{$proc->table}) {
if ($_->pid eq $pid) {
push (@results, $_->size) if exists $fields{'size'};
push (@results, $_->pctmem) if exists $fields{'pctmem'};
return @results;

Perl monks
Perl monks

5 Dec 2010

Facebook Puzzle - Perl - Breathalyzer

Facebook puzzle Breathalyzer can be solved easily using Levenshtein distance calculation Algorthim. More details about this algorithm is here Levenshtein distance

If you are trying to solve using Perl have a look at Text::Levenshtein

This module is available in cpanText::Levenshtein

Facebook Puzzle - Perl - hoppity

Facebook has added Puzzles section under its careers section. You can follow this procedure to get your test puzzle submission done.

1. Save this script in a file hoppity.


use strict;
use warnings;

my $fh;

my $path = $ARGV[0];

die("Missing Filename. Run $0 \n") if(! $path);
die("File not found ") if(! -f $path);

open($fh,"<$path") || die("Error reading file");
my $number = <$fh>;

$number = trim($number);

die("Invalid input $number") if($number !~ /\d+/);

$\ = "\n";
for(my $i=1;$i<=$number;$i++) {
if ($i % 3 == 0 && $i % 5 == 0) {
print "Hop";
} elsif ($i % 3 == 0) {
print "Hoppity";
} elsif ($i % 5 == 0) {
print "Hophop";

sub trim {
my ( $str) = @_;
$str =~ s/^\s*//g;
$str =~ s/\s*$//g;
return $str;

2. Send this file to 1051962371@fb.com with the file attached and subject as hoppity

3. After four hours facebook puzzle bot will reply you with your submission results

2 Dec 2010

Perl Best practices - Coding

Ten Essential Coding Practices by Damien conway in PBP book

1. Always use strict and use warnings.

2. Use grammatical templates when forming identifiers.

3. Use lexical variables, not package variables.

4. Label every loop that is exited explicitly, and every next, last, or redo.

5. Don’t use bareword filehandles; use indirect filehandles.

6. In a subroutine, always unpack @_ first, using a hash of named arguments if
there are more than three parameters.

7. Always return via an explicit return.

8. Always use the /x ,/m , and /s flags, and the \A and \z anchors.

9. Use capturing parentheses in regexes only when deliberately capturing, then give
the captured substrings proper names.

10. Never make variables part of a module’s interface.

Perl Best practices - Development

Ten Essential Development Practices

1. Design the module’s interface first.

2. Write the test cases before the code.

3. Create standard POD templates for modules and applications.

4. Use a revision control system.

5. Create consistent command-line and configuration interfaces.

6. Agree upon a coherent layout style and automate it with perltidy.

7. Code in commented paragraphs.

8. Throw exceptions instead of returning special values or setting flags.

9. Add new test cases before you start debugging.

10. Don’t optimize code—benchmark it.

vimrc for Perl coding from PBP by damien conway

vim is the desired editor for most of the Perl programmers. This .vimrc is recommended by Damien conway in Perl Best practices book

set autoindent "Preserve current indent on new lines
set textwidth=78 "Wrap at this column
set backspace=indent, eol, start "Make backspaces delete sensibly
set tabstop=4 "Indentation levels every four columns
set expandtab "Convert all tabs typed to spaces
set shiftwidth=4 "Indent/outdent by four columns
set shiftround "Indent/outdent to nearest tabstop
set matchpairs+=<: > "Allow % to bounce between angles too
"Inserting these abbreviations inserts the corresponding Perl statement. . .
iab phbp #! /usr/bin/perl –w
iab pdbg use Data: : Dumper ' Dumper' ; warn Dumper [ ] ; ^[ hi
iab pbmk use Benchmark qw( cmpthese ); ^Mcmpthese -10, {}; ^[ O
iab pusc use Smart: : Comments; ###
iab putm use Test: : More qw( no_plan );
iab papp ^[ : r ~/. code_templates/perl_application. pl^
iab pmod ^[ : r ~/. code_templates/perl_module. pm

29 Nov 2010

Desktop application with Perl

Ever wondered how to create pretty looking windowing applications without perltk? The answer is wxPerl. wxPerl is a perl module that allows a Perl program to use the wxWidgets GUI toolkit. If you don't know anything about Perl or wxWidgets, you may find a short explanation below. If you want to learn more, go to wxWidgets. In short wxPerl allows you to write portable GUI applications in Perl, using the wxWidgets object oriented interface. Look at the screenshots.


wxWidgets gives you a single, easy-to-use API for writing GUI applications on multiple platforms. Link with the appropriate library for your platform (Windows/Unix/Mac) and compiler (almost any popular C++ compiler), and your application will adopt the look and feel appropriate to that platform. On top of great GUI functionality, wxWidgets gives you: online help, network programming, streams, clipboard and drag and drop, multithreading, image loading and saving in a variety of popular formats, database support, HTML viewing and printing, and much much more.

ldapsearch encoding issues

Ever wondered why your ldapsearch results are base64 encoded for some values? ldapsearch does a base64 encoding while returning values if there is a space in the end or in the front. It also encodes the value when there is a special character in the value. To get the proper decoded value I would recommend using Net::LDAP which decodes the value while returning via Net::LDAP::Entry

Perl Monks Head Lines - 29-Nov-2010

Perl Monks Head Lines

1. Renaming an image file

2. why need my in a foreach loop?

use strict;
use 5.010;

foreach my $word (qw(abc def ghi)) {
say $word;

When using strict perl requires to declare even the loop variable of a foreach loop. Why is that? After all the $word v

3. Array values into a database help!

4. Get CID inline attachments with MIME::Parser

I have a postfix server which mailbox_command's into this perl script:


use MIME::Parser;

$parser = new MIME::Parser;
$foldername = time().int(rand(10)).int(rand(10)).int(ran

5. default hash name for GetOptions

I want to use GetOptions('foo','bar'), which provides default variables $opt_foo and $opt_bar.

Is there also a default hash provided with this call such as $opts{foo} ?
I realise I could do GetOpti

6. Help using Find::File::name

I'm a perl noob
I'm trying to inventory a bunch of file with .wgt extension and store the matches (from some seeded input) in a report at the end. I need the full path that Find::File::name provides

7. removing duplicates from a string list

8. URL-String-concatenation within Perl [applying to a loop]

Hello dear Perl-monks - good evening!

well i am currently workin on a parser that should fetch pages: i want to do it with Perl since this is the most pretty way to do it!

well - i have to build

9. cookie ssss

Thank you everyone for all your help

This is not a Perl question , but does any one know where to get a Firefox cookie
editor for Linux

Does anyone know where to find good informat

10. Getting range from N..end with list slice

A friend told me that there is some sort of new list slice range syntax in Perl 5.10 that would allow getting a range starting at some offset continuing thru to the last element in a list - no matter

11. "use 5.10.0" creates weird syntax error on sub named "default"

Hi Monks,

I am running 5.10.0 (on Mac Os), and I get a weird behavior. I wan't able to find any explanation so far, and I am quite puzzled. Before I file a bug report, I would like to seek your imme

12. Strange Behavior with XML::Simple when pulling info out of an XML file

I'm very lost. I am trying to do the following:
I have an XML file from Nagios. Here's the structure:

4 check_bigip_pool_connection
5 0
6 1
7 cur

26 Nov 2010

Perl Monks Head Lines - 26-Nov-2010

Perl Monks Head Lines

1. Attachments in emails and finding matches and cross referencing

1st question:
Is there a library out there to read SMTP messages (written to disk in text form with attachments still encoded in various ways) and reliably extract the names of any attachments from t

2. Build Perl with glib1 or glib2

Venerable Monks,

I am compiling Perl 5.10.0 and Perl 5.12.2 on Solaris 8 (and later on Solaris 10). To support this, I have downloaded several packages required by GNU C++ (gcc) from www.sunfreewar

3. PAR::Packer fails to find dependencies when executed

I have encountered an issue which appears to be a bug in the Solaris build of PAR::Packer and may previously have shown up under BSD as well but works fine under Linux

Solaris run

bash-2.05$ pp -o

4. Calculating cross-correlation

5. find & replace a string in perl

Hi monks, i am struggling with editing a file , Iam opening a file and replacing string with a comment(#) at start of that line for example: i have a test.txt file in that there is string called "te

6. error showing LWP request failed

7. Search pattern from end of line


I need a perl reg-expression which extracts the pattern as below.

Basically we want to parse and extract the rpms from the packages.xml inside RHEL cd hence looking for a pattern which extrac

8. Selenium-rc Perl


Using Selenium I cam log into the wepage and get into home page. But I want to understand if it is possible to do following,

In home page When I give the name of third party pro

9. SQL Server parser

I am following the book "Real World SQL Server
Administration with Perl" by Linchi Shea. He has used
5.6.1 from ActiveState.com; Current / latest version
available is

10. Parsing command line options without knowing what they are

Greetings monks,

This seems like such a simple idea, but I can't seem to find any module that does it. I have a script that needs to take in a bunch of command line options in an open-ended set. I

11. Problems with INET, Select, and Win32

I have been trying to make the following code work without success. It is a simple thread waiting on a UDP port. I have lots of possible devices that may send packets to the port which are then simpl

12. SOAP::Lite returning a 404-error for a known-good URL

Hello all,
I am trying to convince SOAP::Lite to post to a .NET WCF web service. I expected interop problems, but I'm hitting a wall even sooner than I expected. When I try to POST the request,

25 Nov 2010

How to extract Headlines from Perlmonks

Do you want to visit perlmonks site only when you see an interesting posting? Here is a simple script which gets the headlines from perlmonks and gives corresponding link.
If you are interested then just go to the link. This takes .01 sec to get the headlines from perlmonk site.

use XML::Simple;
use LWP::Simple;
my $xml = get("http://www.perlmonks.org/headlines.rdf");
my $xs = XML::Simple->new();
my $ref = $xs->XMLin($xml);
my @items = @{$ref->{item}};
print "Perl Monks Head Lines \n\n";
foreach $item (@items) {
print "$item->{link} - $item->{title}\n";

PerlMonks Headlines - 25-Nov-2010

Perl Monks Head Lines

1. [OT] Providing a Windows ppm repo at minimal cost
2. Getting element from List box in Perl tk
3. how to nullify case sensitivity
4. how to find last word match ?
5. check which files are open to write/read by another process
6. how to read every 10 line from input text file ?
7. Poor man's transaction construct
8. Apache::ReadConfig and RewriteRules
9. Storable.pm - corrupt when saving to non-truncated file
10. Find First character of each word in a string
11. NET::SSH2 Terminates
12. Great learning experience

24 Nov 2010

Operational LDAP attributes

Net::LDAP search don't return operational attributes by default. Then how to get operational attributes like createTimestamp, modifyTimestamp from Net::LDAP search ?. Specifying '*' in the attrs list will get the operational parameters. But Net::LDAP documentation says, '+' is used by some servers to request "all operational attributes".

$mesg = $ldap->search( ... ,
attrs => [

19 Nov 2010

Net::LDAP made ldap interaction easy

Net::LDAP module by Graham Barr made Perl interaction with LDAP server very easy. This module is rated 4 stars as some folks feel this module is little slow. I would definitely rate 5 star for this module.

This module can be used to build tools to convert directory data to other format such as csv. This can also be used to convert ldif data to other system format.

Review for this module is available in cpanratings.perl.org

Module can be downloded from cpan

There is a pretty good document on how to use Net::LDAP in perlmonks