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.

Advertisements

6 thoughts on “Copyright header substitution script powered by perl.

  1. 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);
    }

    Like

  2. A bit shorter version:
    #!/usr/bin/perl -lp0i
    s!/\*(?:.|[\r\n])*?\*/!/*
    *
    * This is my new copyright header. (c) 2007
    * All rights reversed.
    *
    */!;

    Like

  3. 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.

    Like

  4. 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.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s