繁体   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