Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the exact full path to a file in Perl

Tags:

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: The full path is /abc/def/ghi/jkl/mno/pqr/myfile.txt

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

like image 374
Steven Avatar asked Sep 05 '12 23:09

Steven


People also ask

How do I write a file path in Perl?

To open a file that's in another directory, you must use a pathname. The pathname describes the path that Perl must take to find the file on your system. You specify the pathname in the manner in which your operating system expects it, as shown in the following examples: open(MYFILE, "DISK5:[USER.

How do I get the current directory in Perl?

my $cwd = getcwd(); Returns the current working directory.


1 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.

like image 186
raina77ow Avatar answered Oct 19 '22 09:10

raina77ow