Relative absolute perl path

The following directory setting:

/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 Directory:

 /dir/dirb ./myprog.pl -p testa/myfilesdir 

Loop through files

 while (my $file_to_proc = readdir(DIR)) { ... $file_to_proc = file1.txt $file_to_proc = file2.txt 

I want

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

I tried several different perl modules (CWD rel2abs), but it uses the current directory. I cannot use the current directory because input can be a relative or absolute path.

+7
source share
1 answer

Use the module File::Spec . Here is an example:

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

Run it like this:

 perl script.pl mydir/* 

And it will print absolute file paths.


UPDATED with a more efficient program. Thanks to the TLP suggestions.

 use warnings; use strict; use File::Spec; for ( @ARGV ) { if ( -f ) { print File::Spec->rel2abs( $_ ), "\n"; } } 
+9
source

All Articles