简体   繁体   English

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

[英]Perl: Replace multiple strings in text line with foreach loop and substitute

This is my goal: 这是我的目标:

  1. Find specific files and save 查找特定文件并保存

    a) foldername a)foldername

    b) filename with full path b)具有完整路径的文件名

  2. For each file, use the file name and folder name to replace two text strings in a file and write the result to an array (later to a file) 对于每个文件,使用文件名和文件夹名替换文件中的两个文本字符串并将结果写入数组(稍后到文件)

but I am obviously missing something because my foreach loop is not working. 但我显然遗漏了一些东西,因为我的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;

The problem is here: 问题出在这里:

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

if I set 如果我订

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

but all that is written to @command_files: 但所有写入@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

I want: 我想要:

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

Why is the foreach loop only bringing the first content in array @files? 为什么foreach循环只将第一个内容带入数组@files?

You modify $command_template with your substitution. 您可以使用替换修改$command_template The second time through the loop it doesn't match. 第二次通过循环它不匹配。

Make a copy of $command_template inside the loop and then do $copy =~ s/filepath/$_/g . 在循环中制作$command_template的副本,然后执行$copy =~ s/filepath/$_/g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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