perl 中是否有相當于 shell 的“pwd -L”?
我想要符號鏈接未決議的當前作業目錄?
我當前的作業目錄是“/path1/dir1/dir2/dir3”,這里 dir1 是指向 test1/test2 的符號鏈接。我希望通過 perl 腳本將當前作業目錄設為“/path1/dir1/dir2/dir3”。我得到的是/path1/test1/test2/dir2/dir3。
如何使當前作業目錄成為未決議符號鏈接的路徑?換句話說,我想實作 shell 的pwd -L.
uj5u.com熱心網友回復:
使用 perl 反引號運算子在您的系統上運行 pwd -L 命令并將輸出捕獲到變數中,這適用于我的系統:
perl -e 'chomp( my $pwdl = `pwd -L` ); print "$pwdl\n";'
uj5u.com熱心網友回復:
嘗試使用 just 來復制bash's 的pwd內置行為perl(特別是在 thePath::Tiny和 coreCwd模塊的幫助下):
首先,從外殼help pwd中:bash
- -L 列印
$PWD當前作業目錄的值- -P 列印物理目錄,不帶任何符號鏈接
(GNU coreutils 版本pwd(1)還讀取 PWD 環境變數以實作-L,這就是為什么qx//即使它無法訪問 shell 的內部變數來跟蹤其作業目錄和路徑,也可以運行它的原因)
$ pwd -P # First, play with absolute path with symlinks resolved
/.../test1/test2/dir2/dir3
$ perl -MCwd -E 'say getcwd'
/.../test1/test2/dir2/dir3
$ perl -MPath::Tiny -E 'say Path::Tiny->cwd'
/.../test1/test2/dir2/dir3
$ pwd -L # Using $PWD to preserve the symlinks
/.../dir1/dir2/dir3
$ /bin/pwd -L
/.../dir1/dir2/dir3
$ PWD=/foo/bar /bin/pwd -L # Try to fake it out
/.../test1/test2/dir2/dir3
$ perl -MPath::Tiny -E 'my $pwd = path($ENV{PWD}); say $pwd if $pwd->realpath eq Path::Tiny->cwd'
/.../dir1/dir2/dir3
作為一個函式(添加了一些檢查,因此它可以處理缺少的$PWD環境變數或指向不存在路徑的變數):
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
use Path::Tiny;
sub is_same_file ($$) {
my $s1 = $_[0]->stat;
my $s2 = $_[1]->stat;
return $s1->dev == $s2->dev && $s1->ino == $s2->ino;
}
sub get_working_dir () {
my $cwd = Path::Tiny->cwd;
# $ENV{PWD} must exist and be non-empty
if (exists $ENV{PWD} && $ENV{PWD} ne "") {
my $pwd = path($ENV{PWD});
# And must point to a directory that is the same filesystem entity as cwd
return $pwd->is_dir && is_same_file($pwd, $cwd) ? $pwd : $cwd;
} else {
return $cwd;
}
}
say get_working_dir;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/412285.html
標籤:
上一篇:日期和時間計算
下一篇:檢查一行中的確切子字串
