RSS
 

Converting paths to absolute in Perl

14 Jan

Here’s a quick fix when working with command line parameters in Perl that will take paths, absolute or relative, as an argument.

For example you execute your script like so:

$./foo.pl -path ./my/path

$./foo.pl -path ../../some/path

$./foo.pl -path /absolute/path

All of which could be possible paths entered by users, you want to support all of them and convert them all to absolute paths in your script. This ensures you script can be called from anywhere, and accept any path given.

– begin scrip –

#!/usr/bin/perl

use Cwd ‘abs_path’;

my $root = $ARGV[1];

$root = abs_path($root);

print “$root\n”;

– end –

Should always print an absolute path, ie- starting with the full path “/some/path”.

VN:F [1.9.3_1094]
Rating: 9.0/10 (4 votes cast)
VN:F [1.9.3_1094]
Rating: +1 (from 1 vote)
Converting paths to absolute in Perl, 9.0 out of 10 based on 4 ratings
Retweet
 
2 Comments

Posted in Personal

 
  1. Anonymous

    March 14, 2005 at 3:11 pm

    Handy. Thanks for the tip. Scott

    VA:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.3_1094]
    Rating: 0 (from 0 votes)
     
  2. redwarp

    June 3, 2010 at 8:24 am

    Pretty cool, thanks

    VA:F [1.9.3_1094]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.3_1094]
    Rating: 0 (from 0 votes)