Perl:用foreach循环替换文本行中的多个字符串并替换

时间:2013-03-27 19:49:49

标签: perl foreach substitution

这是我的目标:

  1. 查找特定文件并保存

    a)foldername

    b)带完整路径的文件名

  2. 对于每个文件,使用文件名和文件夹名替换文件中的两个文本字符串并将结果写入数组(稍后写入文件)

  3. 但我显然遗漏了一些东西,因为我的foreach循环无效。

    use strict;
    use warnings;
    use diagnostics;
    use File::Find::Rule;
    use File::Spec;
    use File::Basename;
    use Cwd;
    my $dir = cwd;
    my $command_template = 'Here is my Filepath: file and this is the Folderpath: folder';
    my $search_file = 'test.txt';
    my @files = File::Find::Rule->file()
                    ->name($search_file)
                    #->maxdepth(2)
                    ->in($dir);
    my @command_files;
    foreach (@files){
        my $directories = dirname ($_);
        $command_template =~ s/file/$_/g;
        $command_template =~ s/folder/$directories/g;
        push(@command_files,$command_template,"\n");
    }
    print "@command_files";
    open COMMAND_FILES, '>command_files.txt' or die "Can't open COMMAND_FILES: $!\n";
    print COMMAND_FILES @command_files;
    

    问题在于:

    foreach (@files){
            my $directories = dirname ($_);
            $command_template =~ s/filepath/$_/g;
            $command_template =~ s/folder/$directories/g;
            push(@command_files,$command_template,"\n");
        }
    

    如果我设置

    @files = qw/ c:\1\test.txt c:\2\test.txt c:\2\1\test.txt /;
    

    但所有写入@command_files:

    Here is my Filepath: c:\1\test.txt and this is the Folderpath: c:\1
    Here is my Filepath: c:\1\test.txt and this is the Folderpath: c:\1
    Here is my Filepath: c:\1\test.txt and this is the Folderpath: c:\1
    

    我想:

    Here is my Filepath: c:\1\test.txt and this is the Folderpath: c:\1
    Here is my Filepath: c:\2\test.txt and this is the Folderpath: c:\2
    Here is my Filepath: c:\2\1\test.txt and this is the Folderpath: c:\2\1
    

    为什么foreach循环只将第一个内容带入数组@files?

1 个答案:

答案 0 :(得分:2)

您可以使用替换修改$command_template。第二次通过循环它不匹配。

在循环中复制$command_template,然后执行$copy =~ s/filepath/$_/g