Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relative absolute path perl

Tags:

perl

Following directory setup:

/dira/dirb
/dira/dirb/myprog.pl

/dira/dirb/testa/myfilesdir Contains the following files

/dira/dirb/testa/myfilesdir/file1.txt
/dira/dirb/testa/myfilesdir/file2.txt

Current dir:

/dir/dirb

./myprog.pl  -p testa/myfilesdir

Cycle through files

while (my $file_to_proc = readdir(DIR)) {
...

$file_to_proc = file1.txt
$file_to_proc = file2.txt

what I want is

$myfile = /dira/dirb/testa/myfilesdir/file1.txt
$myfile = /dira/dirb/testa/myfilesdir/file2.txt

Tried a few different perl module (CWD rel2abs) but it is using current directory. I can not use current directory because input could be relative or absolute path.

like image 602
Paul Avatar asked Apr 27 '12 13:04

Paul


1 Answers

Use module File::Spec. Here an example:

use warnings;
use strict;
use File::Spec;

for ( @ARGV ) { 
    chomp;
    if ( -f $_ ) { 
        printf qq[%s\n], File::Spec->rel2abs( $_ );
    }   
}

Run it like:

perl script.pl mydir/*

And it will print absolute paths of files.


UPDATED with a more efficient program. Thanks to TLP's suggestions.

use warnings;
use strict;
use File::Spec;

for ( @ARGV ) { 
    if ( -f ) {
        print File::Spec->rel2abs( $_ ), "\n";
    }   
}
like image 163
Birei Avatar answered Sep 23 '22 02:09

Birei