简体   繁体   中英

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

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/asdf';

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

从$ newDir删除结尾的斜杠,然后:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM