Okay so I want to delete the first occurrence of a string, let’s say, “dog”, in a file, and only the first occurrence. So if the file reads:
The dog was happy.
The dog liked to run.
The output would be
The was happy.
The dog liked to run.
I have the following code:
#!/usr/local/bin/perl
use warnings;
use strict;
my $file = $ARGV[0];
my $out = $ARGV[1];
open (IN, "<$file");
open (OUT, ">$out");
while(<IN>){
s/dog/ /;
print OUT $_;
}
close IN;
close OUT;
And it works, but instead of repacing just the first instance, it replaces all instances of the word. I thought I had to use the global modifier, g, to make it replace all instances? Why is it replacing all instances of the string I’m searching for? It’s probably some simple error I’m not seeing.
It replaces the first instance each time you evaluate the operator, and you evaluate the operator for each line, so you replace the first instances in each line. Had you used
/g, you would have been replacing all instances in each line.Or as a one-liner:
You can add the file handles back in, but the above accepts a more standard and more flexible usage. To get the same effect as with your code, you just have to use
instead of