如何在 Perl 中找到用户的主目录? [英] How do I find a user's home directory in Perl?
问题描述
我需要检查用户主目录中的文件是否存在,所以使用文件检查:
if ( -e "~/foo.txt" ) {打印是的,它存在!";}
即使在用户的主目录下有一个名为 foo.txt 的文件,Perl 总是抱怨没有这样的文件或目录.当我用 /home/jimmy 替换~"(假设用户是 jimmy)时,Perl 会给出正确的判断.
你能解释一下为什么 "~" 在 Perl 中不起作用并告诉我 Perl 的方法是什么找到用户的主目录?
~
是一个 bash
-ism 而不是 perl
-ism,这就是它不起作用的原因.鉴于您似乎使用的是 UNIX 类型的系统,最简单的 解决方案可能是使用 $HOME
环境变量,例如:
if ( -e $ENV{"HOME"} . "/foo.txt" ) {打印是的,它存在!";}
是的,我知道用户可以更改他们的 $HOME
环境变量,但我假设他们知道他们在做什么.如果没有,他们应得的一切:-)
如果您想以正确的方式进行操作,您可以查看File::HomeDir,它更了解平台.您可以在以下脚本 chkfile.pl
中看到它的运行情况:
使用 File::HomeDir;$fileSpec = File::HomeDir->my_home ."/foo.txt";如果 ( -e $fileSpec ) {print "是的,它存在!
";} 别的 {print "不,它没有!
";}
和成绩单:
<前>pax$ touch ~/foo.txt ;perl chkfile.pl是的,它存在!pax$ rm -rf ~/foo.txt ;perl chkfile.pl不,它没有!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?
~
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!
";
} else {
print "No, it doesn't!
";
}
and transcript:
pax$ touch ~/foo.txt ; perl chkfile.pl Yes, it exists! pax$ rm -rf ~/foo.txt ; perl chkfile.pl No, it doesn't!
这篇关于如何在 Perl 中找到用户的主目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!