如何解析 Perl 中的符号链接?
我有一个符号名称 java 或 jre 或 jre1.5 或 jre1.6 或 java1。 5 或 java1.6 将指向相应的目录。考虑到第一个实例,它看起来像:
java -> /usr/java/jdk1.5.x.x
我的目标如下:
- 检查符号是否存在
- 获取它指向的目录的值
- 使用正则表达式而不是在代码中使用 if-else 语句。
该链接将位于 /usr/tmp 中。
我在 Perl 中编写了一些代码,如下所示:
$filename = "/usr/local/java";
if (-l $filename) {
print "File exists \n";
} else {
print "Not \n";
}
但如果 java 不存在,而是 java1.4 或 java1.5 存在我想搜索哪个应该以 java 开头并且是符号链接。
我还需要获取它指向的目录。请告知如何进行。
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
My aim is as follows:
- To check whether the symbolic exists or not
- To get the value of the directory it is pointing
- To use regular expression instead of using if-else statement in the code.
The link will be in /usr/tmp.
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";
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您确定不想使用
${JAVA_HOME}
环境变量吗?您可以使用内置的 readlink() 函数读取符号链接目标。
要检查其他可能性,您可以将它们全部硬编码并一一检查是否存在,使用
opendir()
/readdir()
内置函数或目标IO:: Dir
查找目录中的所有符号链接并检查它们是否匹配或模式,甚至是glob()
函数,这在您的情况下可能更简单。First of all, are you sure that you don't want to use
${JAVA_HOME}
environment variable?You can read the symlink target using builtin
readlink()
function.To check other possibilities, you may either hardcode them all and check one by one for existence, use
opendir()
/readdir()
builtins or objectiveIO::Dir
to lookup all the symlinks in the directory and check whether they match or pattern, or evenglob()
function which may be simpler in your case.这是链接文件或软链接文件的解决方案。以下代码片段将通过递归解析所有链接来给出链接的原始文件
Here is the solution for the linked files or soft link files. the following snippet will give the original file of the link, by resolving all links recursively