how to get the exact full path to a file in perl

I only have a file name which is myfile.txt and I am not sure where it is saved. How can i get the exact full path where the file is stored. I have tried

$string=`ls /abc/def/*/*/*/*/myfile.txt`;

Result: Full path is /abc/def/ghi/jkl/mno/pqr/myfile.txt

I able to get the full path by running shell command using perl script above. However, this took very long time to return the path. Is that any way to find the full path of the file by using perl?

Answers


Well, if myfile.txt is actually a relative path to that file, there's a core module sub for that - File::Spec->rel2abs():

  use File::Spec;
  ...
  my $rel_path = 'myfile.txt';
  my $abs_path = File::Spec->rel2abs( $rel_path ) ;

... and if you actually need to search through your directories for that file, there's File::Find... but I would go with shell find / -name myfile.txt -print command probably.


You should use the Perl module Cwd to accomplish this. The link has an example also seen below.

#!/usr/bin/perl 
use Cwd;
my $dir = getcwd;
use Cwd 'abs_path';
my $abs_path = abs_path($file);

We can look from anywhere on the system, but in this case we're looking from "/abc/def" folder.

$start_path = "/abc/def/";
@files = <$start_path*/myfile.txt>

foreach $file(@files) {
    print $file; # prints full path of file.
}

I know post was made a year ago, but some might still look at this question.


Use pwd instead of cd in linux to get path of current directory without function,

$path='cd';
$path =~ tr /\\/\//;
chomp($path);
print "$path";

Need Your Help

Can I concurrently write different slice elements

go concurrency slice goroutine

I have a slice that contains work to be done, and a slice that will contain the results when everything is done. The following is a sketch of my general process:

URL Rewrite error with Web Applications

iis-7 web-config url-rewrite-module

I am running an ASP.NET 4.0 website using IIS7 on Windows Server 2008 R2.