JamesT
JamesT

Reputation: 9

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

This is my goal:

  1. Find specific files and save

    a) foldername

    b) filename with full path

  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.

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:

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?

Upvotes: 0

Views: 1104

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54355

You modify $command_template with your substitution. 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.

Upvotes: 2

Related Questions