When a colleague moved a slew of Java classes from one
package to another, he was faced with the hteadache of
having to edit EVERY file in order to change the files'
package names. Instead, I wrote a script for him.

This turns out to be just a specialized form of text replacer.

print<<EOTitle; ###################################################################### +######## # # Rob's import fixer # ###################################################################### +######## EOTitle my $oldPackage = &query( "Which package has moved?" ); my $newPackage = &query( "Where has it moved to? " ); my $file; foreach $file ( <*.java> ) { if (open( IN, $file )) { my @dat = <IN>; close IN; if ( grep( (/^import\s.*$oldpackage/) && (s/$oldPackage/$newPack +age/), @dat ) && open( OUT, ">$file" ) ) { print OUT @dat; close OUT; print "$file updated\n"; } } } sub query { my ($question) = @_; my $reply; print "$question "; chomp( $reply = <STDIN> ); return $reply; }

Replies are listed 'Best First'.
Re: Java Repackager...
by IlyaM (Parson) on Nov 27, 2001 at 04:27 UTC
    Looks like a job for this one liner:
    perl -i -pe 's/^(import\s+)OldPackage/$1NewPackage/' *.java
      If you care about your java, which one might assume based upon your poem, you might want to do:
      perl -i~ -pe 's/^(import\s+)OldPackage/$1NewPackage/' *.java

      --
      perl -p -e "s/(?:\w);([st])/'\$1/mg"

      So is it reasonable to replace the foreach loop with
      a call to perl, containing:

      `perl -i -pe 's/^(import\s+)$oldPackage/$1NewPackage/' *.java`; print "Updated:\n"; print join( "\n", <*.java> );

      I'm wary of calling perl inside perl, because I have
      no idea what really happens (is a new perl interpreter
      spawned? Are there Really Bad side effects? etc.)
      So tell me! Inquiring minds want to know...

      Rob

        My point was that you can replace whole script with this one-liner.

        If you will embed it into some bigger script than it will do cause new perl interpreter to spawn. As for Really Bad side effects: it will be perfomance hit (but you should not care about it in this case) and probably it is not very good style. At least I would not embed such one-liner in my Perl code myself because IMHO embedding Perl code inside Perl code looks somewhat ugly.

        Probably foreach loop could be written slightly shorter but in general your original script is ok. I just wanted to show fast dirty way to do the same.

Re: Java Repackager...
by data64 (Chaplain) on Nov 28, 2001 at 23:33 UTC

    This snippet should be useful as it is. But it would be really cool to have it actually move the files to the new directory structure in accordance with the new package name.

      Well, why didn't you just say so? Here's an uglier
      script that does something similar; namely, it 'clones'
      packages to a new name and location.