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

I'm attempting to search through a file for a certain piece of text, and if it exists, replace it with something else. That part works fine, but here's the catch: if the text isn't in the file, I want to have the script add in some new text at the end of the file. Is there a way to find out if a search and replace like $var =~ s/something/somethingelse/; replaced anything or not?

Replies are listed 'Best First'.
Re: Conditional replace
by busunsl (Vicar) on Aug 23, 2001 at 12:07 UTC
    The s/// operator returns the number of substitutions.
    So something like: do_something() if s/foo/bar/; should do the trick.
Re: Conditional replace
by clemburg (Curate) on Aug 23, 2001 at 12:10 UTC

    Like this:

    try.pl:

    #!/usr/bin/perl -w use strict; my $count = 0; while (<>) { $count += s/foo/bar/g; print; } print "Nothing found!\n" unless $count;

    Show it in action:

    H:\>cat try1.txt bla blurb foo foo foo lilalu H:\>cat try2.txt bla blurb fuu fuu fuu lilalu H:\>cat try1.txt | perl try.pl bla blurb bar bar bar lilalu H:\>cat try2.txt | perl try.pl bla blurb fuu fuu fuu lilalu Nothing found! H:\>

    Christian Lemburg
    Brainbench MVP for Perl
    http://www.brainbench.com

Re: Conditional replace
by lestrrat (Deacon) on Aug 23, 2001 at 12:07 UTC

    Something like this?

    my $add_at_end = 1; while( my $ln = <IN> ) { if( $ln =~ s/str1/str2/ && $add_at_end ) { $add_at_end = 0; } print OUT $ln; } print OUT "text" $add_at_end;
      Your last print has a typo :-) your logic is backwards :-) and its simpler IMO to say:
      my $add_at_end; while (<IN>) { $add_at_end = 1 unless s/str1/str2/; print OUT; } print OUT "text" if $add_at_end;
      Update:And I had a typo also. Fixed mine first :-)
Re: Conditional replace
by George_Sherston (Vicar) on Aug 23, 2001 at 12:58 UTC
    Another way:$FileText =~ s/($Search|$)/$1 eq $Search ? $Replace : $AddText/e;

    § George Sherston
Re: Conditional replace
by October (Initiate) on Aug 24, 2001 at 04:02 UTC
    thanks. works now :)