如何在Perl中找到用户的主目录? [英] How do I find a user's home directory in Perl?

查看:125
本文介绍了如何在Perl中找到用户的主目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查用户主目录中是否存在文件,因此请使用文件检查:

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!" ;
}

即使用户主目录下有一个名为 foo.txt 的文件,Perl始终 抱怨没有这样的文件或目录.当我用/home/jimmy 代替〜"(假设用户是jimmy)时,Perl给出正确的结论.

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.

您能否解释一下为什么〜"在Perl中不起作用,并告诉我Perl的处理方式是什么? 找到用户的主目录?

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

推荐答案

~bash -ism而不是perl -ism,这就是为什么它不起作用的原因.假设您似乎在UNIX类型的系统上,那么最简单的解决方案可能是使用$HOME环境变量,例如:

~ 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!" ;
}

是的,我知道用户可以更改他们的$HOME环境变量,但是我假设他们知道自己在做什么.如果没有,他们应该得到他们得到的一切:-)

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";
}

和成绩单:


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

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

这篇关于如何在Perl中找到用户的主目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆