Monday, January 26, 2009

Adding an external file to a perl module

Let's say you want a perl module to scream "argh" on failure. You find a argh.wav file and want to bundle it with the perl pm file. The problem is loading the wav file without knowing the full path. Perl's current working directory can be any where, and the location of the wav file or module file may not be in the same location as the starting pl file. To find the starting pl file, you can use the FindBin::Bin module, but this doesn't work for modules. If you want to know the location of the module (pm) file instead, you can use the %INC hash to get it. This hash value gets set when you "use" the pm file. Once you know where the pm file is, you can use the dirname() function to get the directory name, then add the name of the wav file.

Here is an example (in a perl module called "Scream.pm"):


use File::Basename;
use Win32::Sound;

my $wavfile = dirname($INC{"Scream.pm"})."/argh.wav";
Win32::Sound::Play($wavfile);

No comments: