How can I resolve a symlink in Perl?

I have a symbolic name java or jre or jre1.5 or jre1.6 or java1.5 or java1.6 that point to the corresponding directory. Given the first instance, it will look like this:

   java -> /usr/java/jdk1.5.x.x

My goal is this:

  • To check if a character exists or not
  • To get the value of a directory indicating
  • Use regular expression instead of using if-else statement in code.

The link will be in / usr / tmp.

I wrote code in Perl that looks like this:

 $filename = "/usr/local/java";
 if (-l $filename) {
        print "File exists \n";
 } else {
        print "Not \n";
 }

But in case java is missing and java1.4 or java1.5 is present instead, I want to do a search that should start with java and is a symbolic link.

I also need to get the directory that it points to. Please advice on how to proceed.

+3
3

, , ${JAVA_HOME}?

symlink readlink().

, , opendir()/readdir() IO::Dir , glob(), .

+10
use Cwd 'abs_path';

$absFilePath = abs_path("$linkPath") ;
+7

-. ,

#!/usr/bin/perl

use warnings;
use strict;

use File::Basename;

my $file='/dev/mapper/vg_ms1-lv_root'; #this should be your input
my $myCwd =`pwd`;
chomp($myCwd);

while ( -l $file ) {
    my $readLnk=readlink( $file );
    #print "$readLnk\n";
    my $directory = dirname( $file );
    my $fileName = basename( $file ); #not doing anything with this name
    #print "$directory\n";
    chdir($directory);
    my $linkPDir = dirname( $readLnk );
    chdir($linkPDir);
    my $next_file = basename( $readLnk );
    my $curDir=`pwd`;
    chomp($curDir);
    $file="$curDir"."/"."$next_file";
}

print "$file\n";
chdir($myCwd);
0

Source: https://habr.com/ru/post/1716776/


All Articles