Perl - Text::Diff
As I stated in my About page I am not a programmer by trade but I can and do code when the need arises. One of my favorite languages to code in is Perl as it provides a ton of functionality thanks to CPAN, is platform-indepandant, and at times very natural and easy going for most tasks I need to accomplish. The thing about Perl though is its Perl and it can be very intimidating at times. Luckily what I needed to do earlier today was not one of those times. Theres always something new to discover using Perl and I’m always glad when I find something new in Perl that is useful or any other language for that matter and today I came across a module that I had never used before so I’d figured I’d share even though it may be a household module for the hardcore perl monks out there.
So my problem was I needed to diff two files and determine if they were identical in order to apply logic based on the output of the diff. Now I do this all the time on the command line using the GNU diff utility but I needed its functionality within Perl. At first I was thinking I could execute a system or exec function but I figured there has to be a better way right? This is Perl after all surely this functionality is available. Well it wasn’t hard to find Text::Diff with a simple search and and after a few minutes of reading the documentation it is exactly what I needed. First things first though. I need to install the module first either via CPAN or my package manager.
Installing on OpenBSD via pkg manager was a snap as long as you have exported the PKG_PATH first.
#export PKG_PATH="ftp://ftp.openbsd.org/pub/OpenBSD/pub/4.2/packages/i386/"
#pkg_add -v p5-Text-Diff
If your on Debian it should be as simple as
#apt-get install libtext-diff-perl
…or from the CPAN shell
cpan>install Text::Diff
With that installed now I just needed the code in my script…
use Text::Diff
my $diff = diff "file1.txt", "file2.txt", { STYLE => "Context" };
if($diff) {
#files are different
...
}
else{
# files are the same.
...
}
…and there it is. I will be sharing the script where I needed this functionality in the near future as part of a feature article I plan to write once my project is near completion. I hope someone may find this to be useful in the meantime.
Leave a Reply