http://www.perlmonks.org?node_id=1002564


in reply to Re^4: trouble with regular expressions
in thread trouble with regular expressions

It isn't a safe thing to do but you could close the file after reading it into your array. Then re-open it for output open $fh, ">", "file.txt" or similar which will clobber (clear the contents) your file then write to it. The danger is that a minor mistake in your program could wipe out or mangle the original file. You could write to a test file until you finish debugging.

Replies are listed 'Best First'.
Re^6: trouble with regular expressions
by programmer.perl (Beadle) on Nov 07, 2012 at 19:53 UTC

    Yes, I made as you wrote: I closed the file and re-open with > property and all are working)) this is our last code

    #!/usr/bin/perl -w use strict; use warnings; use Cwd qw(); my $path = Cwd::cwd(); my $date = localtime(); my $count=0; my $count_file = 0; my $report = "$path/report_$date.txt"; open (FINDIT, "find $path -name '*.js' -type f -print |") || die "Coul +dn't execute find!\n"; while (my $filename = <FINDIT>) { $count_file++; open (TABLETKA, "$filename") || die "Can't open $filename: $!\n"; my @lines = <TABLETKA>; seek(TABLETKA,0,0); my @clean = <TABLETKA>; foreach (@lines) { if ($_ =~ m#(document\.write\('<iframe.*)(</iframe>'\);)#) + { foreach (@clean) { $count++; if ( s{([[:space:]];document\.write\('<iframe.*)(</iframe> +'\);)}{ //eof} ) { close (TABLETKA); open (APP, ">$filename") || die "Can't open FOR WRITING $f +ilename: $!\n"; print APP @clean; close (APP); open (REPORT, ">>$report") || die "Can't open a report.txt +: $!\n"; chomp($filename); print REPORT "$count_file. FILE: $filename\nINFECTED LINE +NUMBER: $count\nCLEANING DATE: $date\n\n"; close (REPORT); $count = 0; } elsif ( s{([^[:space:]])(;document\.write\('<iframe.*)(</i +frame>'\);)}{$1; //eof} ) { close (TABLETKA); open (APP, ">$filename") || die "Can't open FOR WRITING $f +ilename: $!\n"; print APP @clean; close (APP); open (REPORT, ">>$report") || die "Can't open a report.txt +: $!\n"; chomp($filename); print REPORT "$count_file. FILE: $filename\nINFECTED LINE +NUMBER: $count\nCLEANING DATE: $date\n\n"; close (REPORT); $count = 0; } elsif ( s{(;document\.write\('<iframe.*)(</iframe>'\);)}{ +//eof} ) { close (TABLETKA); open (APP, ">$filename") || die "Can't open FOR WRITING $f +ilename: $!\n"; print APP @clean; close (APP); open (REPORT, ">>$report") || die "Can't open a report.txt +: $!\n"; chomp($filename); print REPORT "$count_file. FILE: $filename\nINFECTED LINE +NUMBER: $count\nCLEANING DATE: $date\n\n"; close (REPORT); $count = 0; } } } } }
    Enough codes make shapes. (Hamidjon)