in reply to no reaction on string replace

You should use warnings; Because the default for filehandle is *input*. So when you write open(FILE, "$S") you open the file for reading. You should have been warned about that.

@lines = <FILE> makes a copy of the file content, but for(@lines) doesn't make any copy, inside the for loop $_ is not a copy of a line, it's the line itself. So in the end @lines and @newlines are certainly the same.

Replies are listed 'Best First'.
Re^2: no reaction on string replace
by semipro (Novice) on Sep 10, 2013 at 21:31 UTC
    Hi, thnx! i put the warnings on. While xecuting the cmd interface tells me if he can not find a file. But he can, so the a.txt file adress should be ok. bīBut there is still no effect and no warnings. Your comment on the @ lines sounds convenient, so finally he is copying the old line in the new line and nothing is happening? How can I fix that issue? And here (sorry not the original but the same principle)the code (which has no effect):
    #!/usr/bin/perl -w use strict; my $SCU='C:/Users/name/Desktop/a.txt'; open(FILE, "<$SCU") || die "File not found"; my @lines = <FILE>; close(FILE); my @newlines; foreach(@lines) { $_ =~ s/<ABCD>/xyz/g; push(@newlines,$_); } open(FILE, "$SCU") || die "File not found"; print FILE @newlines; close(FILE);

      You should edit your first post instead of posting your code again. The editing area should appear just below your original post.

      About your posted-again code, there's still no > in your second open, so you can't write on the file. Write open (FILE, ">", "$SCU") or die "Could not open file $SCU: $!";. $! is a special var that contains the error that occurred while trying to open your file.

      If you do not want to modify the output of @lines in your for loop, you can either make an explicit copy with my $copy = $_; or, if you use a recent version of Perl, use the /r switch on the substitution, which means that the result is returned, and the original variable is not affected. If you do not write $var =~ s/pattern/replace/; but just s/pattern/replace; it works on $_ by default BTW. So in your case you could write (if you get an error, your version of Perl is probably too old):  push @newlines, s/<ABCD>/xyz/rg for @lines;

        Hi, I just tried out your tip an I thought I got it..but I guess that is not the case :-(. The Code is now:
        #!/usr/bin/perl -w use strict; my $SCU= 'C:/Users/Desktop/a.txt'; open(FILE, "<$SCU") || die "File not found"; my @lines = <FILE>; close(FILE); #my $copy = $_; my @newlines; foreach(@lines) { push @newlines, s/<test>/xyz/rg for @lines; } open (FILE, ">", "$SCU") or die "Could not open file $SCU: $!"; print FILE @newlines; close(FILE);
        It is still no working. Can you tell me what I messed up? Thank you!