Copyright header substitution script powered by perl.
Most people think that I'm some kind of Python crazy fan, while I actually enjoy learning new programming languages. I haven't write anything useful in perl before, although I've played with it.
But last week I had to replace a lot of copyright/license headers in a bunch of code, and I thought it was a good idea to use perl for it. It took my some effort to find an example on how to do this on the web, so I thought posting the code would be a good idea, enjoy.
#!/usr/bin/perl
foreach $arg (@ARGV) {
open(SOURCE, $arg);
@lines = <SOURCE>;
$source = join("", @lines);
close(SOURCE);
$header = "/*
*
* This is my new copyright header. (c) 2007
* All rights reversed.
*
*/";
$_ = $source;
s/\/\*(?:.|[\r\n])*?\*\//$header/;
$source = $_;
open(SOURCE, ">$arg");
print SOURCE $source;
close(SOURCE);
}
It could be probably less verbose or more perlish, if you have suggestion on how to improve it, feel free to post comments.
Hi Alberto,
I would always recommend to use perl with warnings (-w, or 'use warnings'). This requires you to define every variable you use.
Instead of this '$source = $_' hack you can use '$source =~ s//'.
I didn't test it, but I think then it can look like this:
#!/usr/bin/perl -w
foreach my $arg (@ARGV) {
open(SOURCE, $arg);
my @lines = ;
my $source = join("", @lines);
close(SOURCE);
my $header = "/*
*
* This is my new copyright header. (c) 2007
* All rights reversed.
*
*/";
$source =~ s/\/\*(?:.|[\r\n])*?\*\//$header/;
open(SOURCE, ">$arg");
print SOURCE $source;
close(SOURCE);
}
Posted by: Daniel | 10/31/2007 at 11:58 AM
A bit shorter version:
#!/usr/bin/perl -lp0i
s!/\*(?:.|[\r\n])*?\*/!/*
*
* This is my new copyright header. (c) 2007
* All rights reversed.
*
*/!;
Posted by: prefiks | 10/31/2007 at 12:13 PM
Try not to overwrite the original file directly. You'll be sorry if something goes wrong halfway, then you will have lost half your file.
Instead, write a new file and atomically move it over the old one when you're done.
Posted by: hint | 10/31/2007 at 12:18 PM
Using warnings (use warnings; or -w) doesn't prohibit you from not declaring your variables. use strict; does.
anyway, prefiks's version is probably the most perlish, though it could use the /ms flags on the regexp to simplify it.
Posted by: wolverian | 10/31/2007 at 10:14 PM
Oh, and to hint: while the -i flag doesn't actually do an atomic rewrite, it does create a backup file.
Posted by: wolverian | 10/31/2007 at 10:15 PM
http://refactormycode.com/
Posted by: Scott Robinson | 10/31/2007 at 10:34 PM