Update: I modified my code but it still can't update all the files properly (no compilation issues and I can open/read all the files as well). Can someone please take a look what I am doing wrong. My updated code is below:
I have a follow-on question that I asked earlier. I have a directory named Perl which has three .txt files, namely fil1.txt, file2.txt and file 3.txt.
Content of file 1
line1
line2
TAG1 "some_name:tag1"
line4
TAG2 "some_name:tag2"
line5
TAG3 "some_name:tag3"
Content of file2.txt
line1
line2
TAG1 "some_name_file2:tag1"
line4
TAG2 "some_name_file2:tag2"
line5
TAG3 "some_name_file2:tag3"
Content of file3.txt
line1
line2
TAG1 "some_name_file3:tag1"
line4
TAG2 "some_name_file3:tag2"
line5
TAG3 "some_name_file3:tag3"
I want to replace all the lines that begin with the TAG with "hello_wolrd" such that the line should be something like this:
TAG1 "hello_world"
TAG2 "hello_world_2nd_time"
TAG3 "hello_world_3rd_time".
How do I achieve this? I get the error message that reads "Can't open the file" Here is my code:
#! /usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $dir = "path to my dir";
my @tmp = ();
opendir( my $DIR, "$dir") or die "Can't open directory, $!";
my @list = readdir($DIR);
my @list2 = sort grep(/^.*\.txt$/, @list);
foreach(@list2)
{
push(@tmp, "$_\n");
}
closedir ($DIR);
print ("Tmp = @tmp\n");
foreach my $cur_file (<@tmp>) {
my $fh;
print "Current file = $cur_file\n";
open($fh, '<', "$cur_file") or die "Can't open the file\n";
while(<$fh>){
chomp($_);
my $line = $_;
print "Current line is $line\n";
if($line =~ /Tag1/)
{
$line =~s/\"\S+\"/"hello_world_1st_time"/g;
push(@tmp, "$line\n");
}
elsif($line =~ /Tag2/)
{
$line =~s/\"\S+\"/"hello_world_2nd_time"/g;
push(@tmp, "$line\n");
}
elsif($line =~ /Tag3/)
{
$line =~s/\"\S+\"/"hello_world_3rd_time"/g;
push(@tmp, "$line\n");
}
else
{
push(@tmp, "$line\n");
}
}
close($fh);
# print Dumper @tmp;
open ($fh, '>', "$cur_file") or die "Can't open file\n";
print $fh @tmp;
close($fh);
undef @tmp;
}
Path to perl directory, for instance? It makes a big difference.