开发者

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

开发者 https://www.devze.com 2022-12-30 12:23 出处:网络
I have a string that has a file path: $workingFile = \'/var/tmp/A/B/filename.log.timestamps.etc\'; I want to change the directory path, using two variables to note the old path portion and the new

I have a string that has a file path:

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

I want to change the directory path, using two variables to note the old path portion and the new path portion:

$dir = '/var/tmp';
$newDir = '/users/asd开发者_StackOverflow社区f';

I'd like to get the following:

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


There is more than one way to do it. With the right module, you save a lot of code and make the intent much more clear.

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


Remove the trailing slash from $newDir and:

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


sh-beta's answer is correct insofar as it answers how to manipulate strings, but in general it's better to use the available libraries to manipulate filenames and paths:

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";

gives the output:

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

File::Spec is distributed as part of core Perl. Its documentation is available at the command-line with perldoc File::Spec, or on CPAN here.


I've quite recently done this type of thing.

$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 ));
}
0

精彩评论

暂无评论...
验证码 换一张
取 消