This seems to work fine to me with File::Spec
#!usr/bin/perl
use File::Spec;
$base = '/home/user';
$path = '/home/user/testA/testB';
my $rel_path = File::Spec->abs2rel( $path, $base );
print($rel_path);
Output:
testA/testB
質問
For this problem I found one solution, but I am looking for alternative solutions. Assume I am in directory
/home/user/testA/testB
and my home directory is /home/user
, how can I obtain the path of the current directory relative to my home directory? That is: testA/testB
.
I tried the following:
use Cwd qw(getcwd);
use Env qw(HOME);
my $cdir=getcwd;
my $p=$cdir=~s{^\Q$HOME\E/}{}r;
and it seems to work. My question is if there is a CPAN module for doing this? The closest I came was File::Spec::Functions qw(abs2rel)
but it just gives me ../..
.. maybe I missed something?
解決
This seems to work fine to me with File::Spec
#!usr/bin/perl
use File::Spec;
$base = '/home/user';
$path = '/home/user/testA/testB';
my $rel_path = File::Spec->abs2rel( $path, $base );
print($rel_path);
Output:
testA/testB
他のヒント
Using Path::Tiny:
#!/usr/bin/perl
use warnings;
use strict;
use Path::Tiny;
my $base = '/home/user';
my $path = '/home/user/testA/testB';
my $relative = path($path)->relative($base);
print "$relative\n";