Changing working directory to script location in perl.

Another one of my memo`s. I had some trouble changing the working directory to the actual script location without the need to download all kinds of fancy modules. The solution i found to be working quite nicely was this one.


# We want the programmig to be clean!
use strict;

# We need to change the working directory to where
# the script is. This is how 🙂
# Added by Chris.
use Cwd 'abs_path';
my $path = abs_path($0);
$path =~ s/scriptname.pl//gi;
chdir($path);

Hope this helps anyone 🙂

Advertisements

One thought on “Changing working directory to script location in perl.

  1. Hi Chris.

    I had to tweak the script for Windows 7 Pro(fusion of grief). The path and script name were long enough that it was truncated with ~1.PL. My fix was:
    $path =~ s/srip.*//gi;

    Cheers!
    Scott

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s