agynr has asked for the wisdom of the Perl Monks concerning the following question:

Hello Everyone, I am using the following code to search for the required pattern if in that document .
seek(INPUT,$start_offset_target,0); sysread(INPUT,$target_data,$end_offset_target-$start_offset_target+1 ) +; while ($target_data=~m/$pattern/gi) { $space=''; $c=0; $m = $1; + while($m=~/(\n)/gi) { $c+=1; } $space=' ' x $c; $space.=' ' x length($m); $target_data=~s/$pattern/$space/i; }
Cau plz suggest any further Improvement that can be done . P.S. The $target_data can contain 100000 bytes anf the required $pattern can be found many a times.

Replies are listed 'Best First'.
Re: Replacing the pattern to search for
by mkirank (Chaplain) on Jan 18, 2005 at 13:26 UTC
    you can do it at the command line
    perl -pi -e 's/<your pattern>/" " x (length($&))/eg' file
Re: Replacing the pattern to search for
by sasikumar (Monk) on Jan 18, 2005 at 11:44 UTC
    Hi

    What r u trying to solve. i am not sure why you have two while loops. Please let us know what is the input to it. What would be the output too. This could help us to get to resolve the problem that you face.As far us now i can just understand that you are replacing a pattern with another one that will have space and length of the pattern. Please let us knwo what you want clearly with a example so that we could help you.
    Thanks
    SasiKumar
      Actually the thing is that I want to retain the size of the code by inserting the space whereever that particular $pattern exists. The second while is used as there can be any no. of lines before there the pattern is found.

        So here is the code
        use strict; my $file_name="c:\\temp.txt"; open (FH,"$file_name"); my $pattern="some thing"; my $c=0; my $space=' '; my $line; while(<FH>) { $line=$_; #current line $c++; #counts the number of lines $space=' ' x $c .' ' x length($pattern); #pattern that has to be r +eplaced $line=~s/$pattern/$space/i; }

        Thanks
        SasiKumar
Re: Replacing the pattern to search for
by TedPride (Priest) on Jan 18, 2005 at 15:46 UTC
    Not sure what exactly you're trying to do, but it looks like you want pattern replaced with line number (starting at 1) + pattern length number of spaces. You also want to do this only once per line. In addition, the file is specified as being up to 100000 bytes, which means the file can be loaded into memory all at once instead of being read line by line. The following should work:
    use strict; use warnings; my $path = "c:\\temp.txt"; my $pattern = "some thing"; my $handle; open($handle, $path); my @data = <$handle>; close($handle); my $c = length($pattern); for (@data) { $c++; $_ =~ s/$pattern/' ' x $c/ei; } open($handle, ">$path"); print $handle @data; close($handle);