perl - doing a substitution until certain condition is true -


i'm trying edit text using perl. need make substitution substitution cannot applied once specific word found in text. so, imagine want substitute "hello" forms "goodbye", substitution cannot applied once word "foo" found.

i tried this:

use warnings; use strict; $/ = undef; $filename = shift; open f, $filename or die "usa: $0 filename\n"; while(<f>) { {s/hello/goodbay/} until (m{foo}); print; } close f; 

but, result, first "hello" of text changed.

any suggestion?

trying think efficient. should 1 of following:

s{^(.*?)(foo|\z)}{    $s = $1;    $s =~ s{hello}{goodbay}g;    $s.$2 }se; print; 

or (same above, requires 5.14+)

s{^(.*?)(foo|\z)}{ s{hello}{goodbay}gr . $2 }se; print; 

or

my $pos = /foo/ ? $-[0] : length; $s = substr($_, 0, $pos, ''); $s =~ s{hello}{goodbay}g; print($s); print; 

both work if foo isn't present.

this solution uses less memory:

# assumes foo present # (though expanded handle # assumes foo isn't regex pattern. local $/ = "foo"; $_ = <$fh>; chomp; s{hello}{goodbay}g; print;  print $/;  local $/; print <$fh>; 

Comments

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -