代码之家  ›  专栏  ›  技术社区  ›  wmitchell

如何在具有文件路径的Perl字符串中修改目录?

  •  1
  • wmitchell  · 技术社区  · 15 年前

    我有一个包含文件路径的字符串:

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

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

    我想得到以下信息:

    '/users/asdf/A/B/filename.log.timestamps.etc'
    
    4 回复  |  直到 15 年前
        1
  •  4
  •   sh-beta    15 年前

    从$newDir中删除尾部斜杠,然后:

    ($foo = $workingFile) =~ s/^$dir/$newDir/;
    
        2
  •  5
  •   daxim Fayland Lam    15 年前

    做这件事的方法不止一种。使用正确的模块,可以节省大量代码,并使意图更加明确。

    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
    
        3
  •  0
  •   Community CDub    8 年前

    sh-beta's answer 在回答如何操作字符串方面是正确的,但一般来说,最好使用可用的库来操作文件名和路径:

    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 on CPAN here

        4
  •  -2
  •   Axeman maxelost    15 年前

    我最近做过这种事。

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