Search your unanswered perl queries
Google

Friday, May 8, 2009

Reading a directory Sorting the files

The following post might help the readers to open a directory. skip the current directory . and previous directory .. and considering only the files which needs to be sorted. In files we use Tie::File to tie the records to the file. So whatever we operate on records changes are automatically made to the file.


Sample Function:

use Tie::File;

sub _sort_deployment_files{

my $deploy_dir

opendir(DIR, $deploy_dir);
@files = grep { /^[^\.]/ && -f "$deploy_dir/$_" } readdir(DIR);
closedir DIR;

foreach my $file_name (@files) {
tie my @records, "Tie::File", $file_name, autochomp => 0, mode => O_RDWR;
sort @records;
untie @records;
}

return;
}

Wednesday, December 3, 2008

Redirect to /dev/null

I came across a code snippet like `$ypmatch $host hosts 2>/dev/null` used in one of the perl files I was browsing. Can anyone let me know the significance of redirecting it to /dev/null.

I will post the same when I find it out.

Cleaning A Perl File With REGEXP

Following are the regular expressions which can be used to clean your file of unwanted material

1) Replace all the spaces with nothing.

s/\s//g;

2) Skip the lines with comments.

next if (m/^\#/);

3) skip blank lines

next if (m/^$/);

4) Replace a line in the file which has commented data on a code line.

s/\#.*$//;

5) Replace a line in the file which has data after semicolon

s/\;.*$//;

Wednesday, November 5, 2008

To get current date and time. hh:mm::ss mm/dd/yy

To get the current date and time in the format hh:mm::ss mm/dd/yy and if you are looking for a perl one liner here you go.

perl -e "use POSIX; print strftime qq(%X %x), localtime(time); "

Output is

00:00:51 11/06/08

Thursday, October 30, 2008

Get a date in yyyymmdd format

use POSIX;
my $today = POSIX::strftime('%Y%m%d', localtime);

How to take a hash slice.

If you want to assign some variables of a hash to an array. i.e you want to take some of the elements from hash based on there keys into a array here is a trick\

my %hash = (one => 'one', two => 'two', three => 'three');
my @array ;
@array = @{$hash}{'one','two'};

If you have a hashref and want to take the values of some keys into an array you can do the following.

my $hashref = {one => 'one', two => 'two', three => 'three'};
my @array ;
@array = @{%$hash}{'one','two'};

Getopt::Long :s option specifier

: s option of getopt::long come very much handy when one is looking for the following requirement

1) If a command line option is passed a paramter it is taken as a value for the given option

i.e perl program -option1 value1

$option1 will take value1.

2) If a command line option is not mentioned then variable remains undefined.

i.e perl program

$option1 will remain undef.

3) If a command line option is mentioned but paramter is not passed, then a empty string will be assigned to $option if :s is used and 0 if :i is used

i.e perl program -option1

$option will be q{}... an empty string.

Please take a look at http://search.cpan.org/dist/Getopt-Long/lib/Getopt/Long.pm for further information.

Wednesday, January 30, 2008

Perl is Compiled or Interpreted?

Everyone knows that there are two types of languages interpreted and compiled. Does anyone know what type of language a perl is? If your instant answer is interpreted, maybe this post will make you think otherwise.

When one runs a perl program, perl actually generates a intermediate code called as the bytecode. Now when perl is finished with bytecode where it usually compiles the whole of a program, it takes over the responsibility of being an interpreter and acts accordingly scanning and processing each line of code. So perl is actually an intermediate language. It is neither a strictly compiled language nor a strictly interpreted one.

Tuesday, December 18, 2007

__DATA__ a Virtual File In Perl

It has been occurred a lot of times that one has to test a code using data from a file. It can be anything like checking for a pattern in a file to taking some input. If you want to check the code without opening the file and reading it. One can use the __DATA__ marker provided by perl as a pseudo-datafile.

Steps to follow:
1) At the end of the code use __DATA__ marker and copy paste or write the contents of the file you wish to test exactly from the next line of _DATA_.
2) Use while (){ -- your code here -- }.

#!/usr/bin/perl
use strict;
use warnings;

while () {
chomp $_;
print "Found" if $_ =~ /(t\w+)/;
print $1;
}
__DATA__
hello there how r u

Output of the above program will be “there”.

Note: If you have any queries do leave your comments.

Friday, December 14, 2007

Executing Commands on Remote Machine

Hello Everyone, This time it is not a solution on something. Instead it a a problem which I require a solution to and is related to a critical task at my work. And would require your valuable comments on this.

I want to execute commands on a remote machine via Apache. I will be using the Net::SSH::Perl module to do it. But when I try doing it from shell running the script as root it get executed and the expected results are shown. However when I execute it through CGI with apache as user it doesn't get executed.

After digging it a lot I think it might be the permission issue where apache does not have permissions to execute the script on remote machine. Executing apache script as root will not be secure. SO do you guyz have any comment on this.

Wednesday, November 28, 2007

Regular Expressions : email id

Almost everyone of us have sometime or other tried to write a regular expression for email ids and other stuff. \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

Here is a link to regular expression site which reports various aspects of regular expressions related to perl, shell and many others. It has a classic example of regex for email id.

Tuesday, November 27, 2007

One Liner : List all files of a directory.

If one wants to list all the files and directories from a particular directory here is the onliner for the same. We use IO::ALL for this purpose in this post.

perl -MIO::All -wle "my $io = io('e:/downloads'); print $io->All;"

and the output will list all the directories and files in downloads folder.

Comments and other ways are alwayz a welcome.

Thursday, November 22, 2007

Some Perl Tips

  1. No doubt the first tip is to use strict in whatever code you write. It helps in avoiding the typo and many other errors which otherwise are real difficult to bebug.
  2. When using if it is not necessary to emboss the condition in ()’s when if is used as the last part of the statement.
  3. @ARGV is the array which holds all the parameters passed to a perl program through a command line.
  4. For conditions in perl “”, 0 , “0”, undefined is false, everything else is true.
  5. It is confusing for some people to remember how unless works. One can remember it in a simple way by saying if not this then this happens. i.e unless (people){do this}; can be interpreted as if not people do this.
  6. When you want to comment a large amount of code you can always use a condition which will always be false. eg. if (1 > 2) { ...... }

If anyone of you have any other perl tips which you follow as a practice, please leave it in the comments section. I would like to add it to the list with your name as contributor and let people efficiently do their perl coding.

Friday, November 16, 2007

Perl Module : How to Install Perl Module on Windows

The most simple task to make your tasks simpler is installing a perl module on your machine.
There are three common ways by which one can install a perl module on your machine. Lets see the installation on windows machine in this post.

There is a ppm utility provided with every active state perl installation, atleast I got it with perl Vesion 5.8.X All you have to do is follow the below steps

1) Click Start
2) Click Run
3) Type cmd and press enter
4) Type ppm and press enter
5) Once you get the ppm utility prompt like ppm> type install modulename
eg. install Net::SSH::Perl
The ppm utility will carry the installation of the perl module for you.

There is workaround for this if you don't have ppm utility or want to install the module manually. Download the zip file from cpan and unzip it with unzip utitliy. Go to the respective directory on command prompt and enter the following commands in sequence.

1) c:\>Net-SSH-Perl>perl Makefil.PL
2) c:\>Net-SSH-Perl>nmake
3) c:\>Net-SSH-Perl>nmake test
4) c:\>Net-SSH-Perl>nmake install

And the module will be installed for you.

Do comment on how you install the new perl modules.

Tuesday, November 13, 2007

One Liner : To check if a module is already installed

I have always came at this stop where i needed to check if a module is already installed or if so what is the version of the module.

perl -e "use [modulename]" e.g perl -e "use Net::SSH::Perl" will tell you if the module is installed or not. If its installed nothing happens and you get the prompt to perform new task. If it is not installed perl throws an error somewhat like can't locate Net/SSH/Perl.pm

perl -M[modulename] -e "print $[modulename]::VERSION" will print the current version of the module. e.g perl -MCGI -e "print $CGI::VERSION"
Most of the packages has a package variable as VERSION which holds the version of the module.

However the only true way to determine if a module is correctly installed, one can run the test scripts provided in the t folder of the module distribution. If all the scripts can run successfully, then only one can be sure that a particular module is installed fully or properly.

Do let us know what method do you use to see if a perl module is installed on your machine.

Monday, November 12, 2007

One liner to shutdown a windows pc using perl

To shutdown a pc using perl one can write a one liner at command prompt as below

perl -e "sleep(3600); system('shutdown.exe -s')"

Thats it... the sleep(3600) will make the program sleep for 1 hour i.e 3600 seconds. According one can schedule the shutdown delay and have a peacefull sleep or walkaround in the park.

Hello Perlies!!!

Hello to all the perl people out there. I have worked on perl for quite a while now and would really like to share some of my findings which might be helpfull to atleast few of perl programmers across the world.