Friday, July 6, 2007

Perl In Batch Clothing

As someone who writes a lot of scripts, Perl is my language of choice. But it does not mean I can live without Windows batch. Sometimes though, it is necessary to combine the two by disguising a Perl script as a batch file.

When might this come in handy? Well, to be honest I can't really think of any right now, but this is certainly cool. This trick is not a batch file trick per se. It's really a Perl trick, and you'll see soon enough why that is. But I'd like to put it here just the same because hey, it's got some batch scripting in it.

To write your Perl script as a batch file, all you have to do is add a few lines at the top of your Perl script, rename the script extension to .bat or .cmd, and you're done.

@echo off

perl -x %~dpf0 %*

exit /b %errorlevel%


use strict;

print "Hey $ARGV[0] I'm in Perl!\n";

exit 0;

This file, being a batch file, is executed by the command processor as any batch file. It reads each line and executes that line.

The first line is straightforward. The second line is really the trick. Doing perl -x tells Perl to read the file you pass as argument, %~dpf0, which is the complete path of the batch script, and ignore anything in the file until it finds the #!perl line. Then it treats it like any other Perl script.

The last argument on that line is simply passing all the command line arguments you pass to your batch script to the Perl as well.

So try and invoke the script. Let's say you named the script foo.bat.

foo.bat Batcheero

You'll see the following printed output.

Hey Batcheero I'm in Perl!

Like I said, not much real use I can think of, but it's nifty all the same.


the.dub said...

This was VERY helpful for me today. I couldn't get perl to accept the command line arg in a scheduled task for the life of me...turning it into a 'batch' file did the trick ;)

Unknown said...

Hi Friends
Hope This also will work fine

1)create a perl script.

2)call the perl in batch as below

@echo off

/danger said...

Hi all, I am trying to execute a perl command (search and replace) from a batch file, but I would like to use a variable like this:

set var vol = 36

perl -pi.bak -e s/volume/volume %vol%/g inputfile.txt

any ideas?