Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I resolve a symbolic link in Perl?

Tags:

symlink

perl

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:

  1. To check whether the symbolic exists or not
  2. To get the value of the directory it is pointing
  3. 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.

like image 238
PJ. Avatar asked Nov 28 '22 20:11

PJ.


2 Answers

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 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.

like image 65
Michał Górny Avatar answered Dec 20 '22 10:12

Michał Górny


use Cwd 'abs_path';

$absFilePath = abs_path("$linkPath") ;
like image 23
mms Avatar answered Dec 20 '22 11:12

mms