1

I'm trying to remove the first C-style comment (only the first) from a collection of Java source files. At first I tried a multi-line sed, but that didn't work properly so after some Googling it seemed Perl was the way to go. I used to like Perl, it was the first language I ever used to make a web program with, but I've run into a wall trying to get this script to work:

#!/usr/bin/perl -i.bak

$s=join("",<>);
$s=~ s/("(\\\\|\\"|[^"])*")|(\/\*([^*]|\*(?=[^\/]))*\*\/)|(\/\/.*)/$1 /;
print $s;

I call it with the filename(s) of the files to be processed, e.g. ./com.pl test.java. According to everything on the Internet, -i (in-place edit) should redirect output from print statements to the file instead of printing to stdout. Now here's the thing: it doesn't. No matter what I try, I can't seem to get it to replace the file with the print output. I've tried $^I too but that doesn't work either.

I don't know if it's relevant but I'm on Ubuntu 11.04.

P.S. I'm aware of the pitfalls of regexing source code :)

Dave
  • 556
  • 1
  • 6
  • 17
  • 1
    See http://stackoverflow.com/questions/877470/how-can-i-strip-multiline-c-comments-from-a-file-using-perl for inspiration... – Fredrik Pihl Aug 29 '11 at 09:54

1 Answers1

1

Does the following not work from the command line?

$ perl -pi.bak 's|your_regex|here|' *.java

Inside a script

The script equivalent of the above is:

#!/usr/bin/perl -pi.bak
s|your_regex|here|;

The original post was missing the p flag, as pointed out by triplee in his comment.

See perldoc perlrun for more.

Community
  • 1
  • 1
Zaid
  • 36,680
  • 16
  • 86
  • 155
  • That works - it's when I try to do in-place inside a Perl script that it stops working. :( – Dave Aug 29 '11 at 10:14
  • 1
    That's right, you need to have `-n` or `-p` in order for `-i` to know what to do. You'll probably want to add `-0777` to make it slurp the whole file. – tripleee Aug 29 '11 at 10:46
  • Thanks! The solution above works (I added the -0777 too). I have massive respect for people who fully grok Perl scripting. :) – Dave Aug 29 '11 at 11:29
  • @Dave : I'm not so sure about 'fully'... we learn something new every day ;) – Zaid Aug 29 '11 at 14:19