0

I have a file like test.l

car ( "kia"
max speed
min speed
price "XXX"
)
bike ( "R1"
max speed
min speed
price "YYY"
)

I want to remove the quotes in the line having 'price'. I have been trying to do that using :

use strict;

open FILE, "<<test.l";
#open (FILE2,">>test.l");

while (my $string = <FILE>) {

    if ($string =~ m/^price/ig) {

        $string =~ s/\"//ig;
        print  FILE $string;
    }
}
close FILE;
#close FILE2;

Can i overwrite the input file with the modified line when 'price' is encountered??? The above code just print the input without any change.

2 Answers 2

3

No, it's not really possible. You have to create a temporary file. This following trick will create the temporary file for you:

local @ARGV = 'test.1';
local $^I = '';          # Use .bak on Windows
while (<>) {
   s/"//g if /^price/;
   print;
}

It's basically the same as doing

perl -i -pe's/"//g if /^price/' test.1
3
  • @ysth, tr/"//d, I think? I never use it.
    – ikegami
    Sep 25, 2012 at 4:46
  • I had to reread the question a couple of times to understand what you were referring to as being not possible. Still not clear for me.
    – Zaid
    Sep 25, 2012 at 5:58
  • @Zaid, He wants to read from and write to a single file. Generally, speaking that's not possible (or at least complex and crazy slow), although I suppose it would be in this case since he's always replacing with something shorter. So I recommended he write the output to a temporary file and rename it over the old one, and showed how to do that easily.
    – ikegami
    Sep 25, 2012 at 7:10
0
perl -ne 'if(/^price/){s/\"//g;}print' your_file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.