簡體   English   中英

如何修改具有文件路徑的Perl字符串中的目錄?

[英]How can I modify the directory in a Perl string that has a file path?

我有一個具有文件路徑的字符串:

$workingFile = '/var/tmp/A/B/filename.log.timestamps.etc';

我想更改目錄路徑,使用兩個變量來記錄舊路徑部分和新路徑部分:

$dir = '/var/tmp';
$newDir = '/users/asdf';

我想得到以下內容:

'/users/asdf/A/B/filename.log.timestamps.etc'

有多種方法可以做到這一點。 使用正確的模塊,您可以節省很多代碼,並使意圖更加清晰。

use Path::Class qw(dir file);

my $working_file = file('/var/tmp/A/B/filename.log.timestamps.etc');
my $dir          = dir('/var/tmp');
my $new_dir      = dir('/users/asdf');

$working_file->relative($dir)->absolute($new_dir)->stringify;
# returns /users/asdf/A/B/filename.log.timestamps.etc

從$ newDir刪除結尾的斜杠,然后:

($foo = $workingFile) =~ s/^$dir/$newDir/;

sh-beta的答案是正確的,因為它回答了如何操作字符串,但是通常最好使用可用的庫來操作文件名和路徑:

use strict; use warnings;
use File::Spec::Functions qw(catfile splitdir);

my $workingFile = '/var/tmp/A/B/filename.log.timestamps.etc';
my $dir = '/var/tmp';
my $newDir = '/usrs/asdf';

# remove $dir from $workingFile and keep the rest
(my $keepDirs = $workingFile) =~ s#^\Q$dir\E##;

# join the directory and file components together -- splitdir splits
# into path components (removing all slashes); catfile joins them;
# / or \ is used as appropriate for your operating system.
my $newLocation = catfile(splitdir($newDir), splitdir($keepDirs));
print $newLocation;
print "\n";

給出輸出:

/usrs/asdf/tmp/filename.log.timestamps.etc

File :: Spec是Perl核心的一部分。 其文檔可在命令行中使用perldoc File::Spec在CPAN上獲得

我最近做了這種事情。

$workingFile = '/var/tmp/A/B/filename.log.timestamps.etc';
$dir         = '/var/tmp';
$newDir      = '/users/asdf';

unless ( index( $workingFile, $dir )) { # i.e. index == 0
    return $newDir . substr( $workingFile, length( $dir ));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM