简体   繁体   English

使用Perl检查〜/中是否存在目录

[英]Check if directory exists in ~/ using Perl

I noticed strange behavior of the -d flag to check if a file is a directory and if the directory exists. 我注意到-d标志的奇怪行为,以检查文件是否是目录以及目录是否存在。 It behaves differently when using ~/my_dir as my path. 使用~/my_dir作为我的路径时,它的行为有所不同。

The following code will return false, even though the directory my_dir exists, but if I'll change it to a full path like /home/ricky/my_dir , then the if statement will return true. 以下代码将返回false,即使目录my_dir存在,但如果我将其更改为完整路径,如/home/ricky/my_dir ,则if语句将返回true。

#!/usr/bin/perl -w
#
use strict;

if ( -d "~/my_dir") {
    print "Found \n";
}
else {
    print "Not found \n";
}

What's the difference? 有什么不同?

~ is a shell shortcut to indicate the home directory, it is unknown to perl. ~是一个shell快捷方式,用于指示主目录,perl是未知的。 You have to use the environment variable HOME here -- for instance using "$ENV{HOME}/my_dir" . 您必须在此处使用环境变量HOME - 例如使用"$ENV{HOME}/my_dir"

~ is not a real path. ~不是真正的道路。 Shells such as /bin/bash expand it to the value of the $HOME environment variable. 诸如/bin/bash shell将它扩展为$HOME环境变量的值。 Perl does not. Perl没有。 So, you should use something like this instead: 所以,你应该使用这样的东西:

if ( -d "$ENV{HOME}/my_dir" ) {
    ...
}

You can check by executing the chdir command also. 您也可以通过执行chdir命令来检查。 chdir "dir_name" will return 0, if directory is not present. 如果目录不存在,则chdir“dir_name”将返回0。 And 1 if directory is present. 如果目录存在,则为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM