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šŸ™‚

About Chris Gralike

Momenteel ben ik manager van de afdeling business continuity bij de zakelijke IT dienstverlener AMIS Services BV. Sinds 2003 ben ik actief in de ICT branche. Tussen 2003 en nu heb ik verschillende rollen vervuld. In de rollen: systeem- en netwerkbeheer, system engineer, servicemanager en nu practice manager ben ik in contact gekomen met uiteenlopende technologieƫn, methodologieƫn, ideeƫn, oplossingen en innovaties. Een rijke ervaring waarmee ik de klanten van Conclusion en AMIS elke dag probeer te ondersteunen. Mijn credo: 'Altijd opzoek een win-win tussen business en technologie.'

Posted on December 4, 2009, in Linux, Linux Commands. Bookmark the permalink. 1 Comment.

  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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: