in reply to Matching Question

Are you trying to replace "go" with "/" on lines that start with "go"? If so, you should be matching against $_, not $text. Also, you never use $text after you do the substitution... if you want something useful, you should do something, like print the line. This probably doesn't do exactly what you want, but here's my best shot:
# print each line after replacing "go" with "/" while (<FILE>) { $count++ if s/^go/\//; print; } print STDERR "There were $count lines starting with 'go' in this file\ +n";

-- Mike

--
just,my${.02}

Replies are listed 'Best First'.
Re: Re: Matching Question
by curtisb (Monk) on Sep 20, 2002 at 18:50 UTC
    OK, that worked, but how do I write it back to the same file?
    Bobby
      Hmmm... if this is the entire script, you could simply pass the filename as a parameter and use the -p and -i switches, something like this:
      #/usr/bin/perl -pi.bak $count++ if s/^go/\//; END { print STDERR "There were $count lines starting with 'go' in the +file\n"; }
      This will automatically overwrite your original file with the new, substituted lines. It will also create a backup file named "<file>.bak" just in case. :-)

      If this is not your entire program, then you can just capture its output to a new file, then rename the new file to have the same name as the old one. You could have your program do this itself by printing its output to a new file, then renaming that file. Maybe something like this (this is not the whole program, of course):

      open FILE, "< $file" or die "Can't open input file: $!\n"; open OUT, "> '$file.new'" or die "Can't open output file: $!\n"; while (<FILE>) { $count++ if s/^go/\//; print OUT; } close OUT; close FILE; print STDERR "There were $count lines starting with 'go' in the file\n +"; rename $file, "$file.bak"; # make backup copy rename "$file.new", $file; # overwrite original file

      -- Mike

      --
      just,my${.02}