如何解析 Perl 中的符号链接?
我有一个符号名称 java 或 jre 或 jre1.5 或 jre1.6 或 java1.5 或 java1.6 将指向相应的目录.考虑到第一个实例,它看起来像:
I have a symbolic name java or jre or jre1.5 or jre1.6 or java1.5 or java1.6 that will point to the respective directory. Taking into account the first instance, it will look like:
java -> /usr/java/jdk1.5.x.x
我的目标如下:
- 检查符号是否存在
- 获取它指向的目录的值
- 在代码中使用正则表达式代替 if-else 语句.
链接将在 /usr/tmp 中.
我用 Perl 写了一些代码如下:
I wrote some code in Perl which is as follows:
$filename = "/usr/local/java";
if (-l $filename) {
print "File exists \n";
} else {
print "Not \n";
}
但是如果 java 不存在,而是 java1.4 或 java1.5 存在,我想搜索应该以java 是一个符号链接.
But in case java is not present and instead java1.4 or java1.5 is present I want to search which should start with java and is a symbolic link.
我还需要获取它指向的目录.请建议如何继续.
Also I need to get the directory that it is pointing. Please advice how to proceed.
首先,您确定不想使用 ${JAVA_HOME}
环境变量吗?
First of all, are you sure that you don't want to use ${JAVA_HOME}
environment variable?
您可以使用内置的 readlink()
函数读取符号链接目标.
You can read the symlink target using builtin readlink()
function.
要检查其他可能性,您可以将它们全部硬编码并一一检查是否存在,使用 opendir()
/readdir()
内置函数或目标 IO::Dir
查找目录中的所有符号链接并检查它们是否匹配或模式,甚至 glob()
函数,这在您的情况下可能更简单.
To check other possibilities, you may either hardcode them all and check one by one for existence, use opendir()
/ readdir()
builtins or objective IO::Dir
to lookup all the symlinks in the directory and check whether they match or pattern, or even glob()
function which may be simpler in your case.