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

▼魔方 西西 提交于 2019-11-27 20:58:45

~ is a bash-ism rather than a perl-ism, which is why it's not working. Given that you seem to be on a UNIX-type system, probably the easiest solution is to use the $HOME environment variable, such as:

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

And yes, I know the user can change their $HOME environment variable but then I would assume they know what they're doing. If not, they deserve everything they get :-)

If you want to do it the right way, you can look into File::HomeDir, which is a lot more platform-savvy. You can see it in action in the following script chkfile.pl:

use File::HomeDir;
$fileSpec = File::HomeDir->my_home . "/foo.txt";
if ( -e $fileSpec ) {
    print "Yes, it exists!\n";
} else {
    print "No, it doesn't!\n";
}

and transcript:

pax$ touch ~/foo.txt ; perl chkfile.pl
Yes, it exists!

pax$ rm -rf ~/foo.txt ; perl chkfile.pl
No, it doesn't!
brian d foy

I'm not sure how everyone missed File::HomeDir. It's one of those hard tasks that sound easy because no one knows about all of the goofy exceptions you have to think about. It doesn't come with Perl, so you need to install it yourself.

Once you know the home directory, construct the path that you need with File::Spec:

 use File::HomeDir qw(home);
 use File::Spec::Functions qw(catfile);

 print "The path is ", catfile( home(), 'foo.txt' ), "\n";

You can glob the tilde, glob('~/foo.txt') should work. Or you can use the File::Save::Home module that should also take care of other systems.

The home directory for a user is stored in /etc/passwd. The best way to get at the information is the getpw* functions:

#!/usr/bin/perl 

use strict;
use warnings;

print "uid:", (getpwuid 501)[7], "\n",
    "name:", (getpwnam "cowens")[7], "\n";

To address your specific problem, try this code:

if ( -e (getpwuid $>)[7] . "/foo.txt" ) {
   print "yes ,it exists!";
}
phoebus
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!