How do I find a user's home directory in Perl?

Viewed 47511

I need to check whether a file in a user's home directory exists so use file check:

if ( -e "~/foo.txt" ) {
   print "yes, it exists!" ;
}

Even though there is a file called foo.txt under the user's home directory, Perl always complains that there is no such file or directory. When I replace "~" with /home/jimmy (let's say the user is jimmy) then Perl give the right verdict.

Could you explain why "~" dosen't work in Perl and tell me what is Perl's way to find a user's home directory?

6 Answers

Fast forward to 2020 and there is now in perl since version 5.31.10 at its core a module called File::Glob which resolves the tilde, such as:

perl -MFile::Glob=":bsd_glob" -lE 'say File::Glob::bsd_glob( "~john" )'

would produce: /home/john

or

perl -MFile::Glob=":bsd_glob" -lE 'say File::Glob::bsd_glob( "~/some/folder" )'

would produce: /home/jack/some/folder

The File::Glob module exist since perl v5.6, but only with the glob subroutine which has been deprecated.

Related