in reply to Re: Replacing an entire line if a substring is found
in thread Replacing an entire line if a substring is found

While you made good points i suspect this is more what he was after

use strict; use warnings; use feature 'say'; while ( my $line = <DATA> ) { chomp $line; say replace( $line, 'SUBSTR', 'FOO' ); } sub replace { my ( $input, $wanted, $replacement ) = @_; if ($input =~ m/$wanted/) { return $replacement;} else { return $input; } } __DATA__ path/to/some/file path/to/some/other/file path/to/SUBSTR/file #replace entire line if SUBSTRING is found path/to/file
Result
path/to/some/file path/to/some/other/file FOO path/to/file

Replies are listed 'Best First'.
Re^3: Replacing an entire line if a substring is found
by 1nickt (Canon) on Apr 26, 2017 at 03:27 UTC

    Lol, oh, is that what "entire line" means? I'm on a plane using my mobile, that's my excuse 😚

    The way forward always starts with a minimal test.

      O2 deprivation, thats it!

Re^3: Replacing an entire line if a substring is found
by victorz22 (Sexton) on Apr 26, 2017 at 06:11 UTC

    Thanks for the help but how would i set up that while statement to iterate through a scalar variable rather than a file handle? I have all my data stored in a scalar variable called $fileContent. So in other words how would i set up the while block using $fileContent rather than <DATA>

    #This is how I read in the file my $fileContent = do { open(my $fileHandle, $inputFile) or die "Could not open file '$inp +utFile' $!"; local $/; <$fileHandle>; };

      Any particular reason it be to be in a single string? an array would be much easier to process and involve less character handling while doing the replacements.

      use strict; use warnings; use feature 'say'; my @lines=<DATA>; for my $line (@lines) { chomp $line; if (index($line, 'SUBSTR') > -1 ) {$line='FOO'; } } #for my $line (@lines) { say $line; } my $fileContent=join("\n",@lines); say $fileContent; __DATA__ path/to/some/file path/to/some/other/file path/to/SUBSTR/file #replace entire line if SUBSTRING is found path/to/file

      I imagine you have seen and copied syntax like:

      my $data = do { local $/, <DATA> };
      ... which Monks use a lot around here to demonstrate solutions using data contained in the script.

      But in your case, if you are interested in handling the lines one at a time, and they exist in a separate file, there's no good reason to combine them all in a scalar.

      open my $fh, '<', $filename or die $!; while ( <$fh> ) { ... # process one line at a time }

      Hope this helps!


      The way forward always starts with a minimal test.