Search code examples
arraysperldata-structuresinsert-updateperl-data-structures

Perl: insert elements of array in file by substitution


1) I have a textfile. The file contains a STRING that needs to be substituted with multiple lines, those lines are elements of an array.

Contents of file:

line 1  
line 2   
line 3  
STRING  
line 4  
...  

2.)I have an array

@array = qw (ele1 ele2 ele3);

This array can have 2 or more elements.

3.)I want to open the file, substitute the STRING with following pseudocode:

s/STRING/@array/;  

and write results in a new file.

4.) The new file with result should look like this :

line 1  
line 2   
line 3  
ele1  
ele2  
ele3
line 4  
...

Here a piece of pseudocode:

open (FILE "< file.txt");
open (OUTPUT "> new.txt");
@array=qw(ele1 ele2 ele3);
for $line (<FILE>) {
    s/STRING/@array/;
    print OUTPUT "$line\n";
}
close FILE;
close OUTPUT;

Any suggestions on how to insert elements of an array into this file using substitution?

I am not looking for solutions based on sed, awk, cat or Unix shell tools.


Solution

  • You could do:

    my $str = "line 1
    line 2
    line 3
    STRING
    line 4";
    my @array = qw (ele1 ele2 ele3);
    $str =~ s/STRING/join"\n",@array/e;
    say $str;
    

    Output:

    line 1
    line 2
    line 3
    ele1
    ele2
    ele3
    line 4