Sunday, December 28, 2008

Perl : Get filename or directory name from an absolute path

Use Perl's File module to get Filename or directory name from an absolute path. Below is an example of how to do this:

#!/usr/bin/perl
use File::Basename;

print getDirPath("/mnt/users/vishnu/blog/PerlPost.html");
print getFileNameWithoutExt("/mnt/users/vishnu/blog/PerlPost.html");
print getFileName("/mnt/users/vishnu/blog/PerlPost.html");

sub getDirPath() {
return dirname($_[0]);
}

sub getFileNameWithoutExt() {
my $file = basename($_[0]);
$file =~ s/\.[^.]*$//;
return $file;
}

sub getFileName() {
return basename($_[0]);
}


Output of above program would be:
/mnt/users/vishnu/blog
PerlPost
PerlPost.html

Saturday, December 20, 2008

Perl error: Can't locate module in @INC

If you get a Perl error message like Can't locate module.pm in @INC, this message means that the Perl module you're trying to include (like the module named module) can't be found in Perl's include path, which is represented by the variable named @INC.

Perl uses an @INC variable that contains the directories it will search in when you specify that you want to include a module, but you can't look at it like an environment variable. Although Perl doesn't have something like the CLASSPATH environment variable you can easily look at, you can print the @INC variable with a simple one-line command. The following Perl command shows the directories that Perl looks in when it tries to load modules:

perl -e 'print join("\n", @INC);'

Including a perl module your @INC include path

There are different ways by which you can add your perl module in @INC include path
1. Specify it in PERL5LIB environment variable
export PERL5LIB=path

2. Perl takes -I option where you can specify the additional directories where it should search for modules.
perl -I path myscript.pl

3. Modify your Perl program to find the module by adding below line near the top of Perl programs. This simple line of code tells your Perl program to add this directory to it's @INC search directory.
use lib "path"

Friday, December 19, 2008

Perl: FileDiff utility

I have 2 csv files (pipe seperated), one column (basically an Id field) is common in both the files. I need to compare both the files on the basis of this common field and print the lines which has common Id, Lines with id which is only in file1 and vice-versa. I thought up for writing perl script for this task. See below script.