Wednesday, November 25, 2009

Perl script to exact packages from multi package Perl module

Here is a little script that I use to extract the individual modules from a multiple package Perl module.

While the script works, it isn't perfect and if you have any comments, have an addendum, etc, please let me know!

The script is below. Please make sure to edit $file, the input file, and $outdir, the destination directory. Good Luck.

#!/usr/bin/perl -w
use strict;
use File::Spec;
use File::Path qw(mkpath);
my $file = '/exact/path/to/perl/module.pm';
my $outdir = '/tmp/';
open(my $fh, '<', "$file") or die $!;
my $contents = '';
my $filename = undef;
while (<$fh>) {
if ( $_ =~ /^package (.*);/g ) {

# construct a new file
$contents = '';

# its filename
$filename = File::Spec->catfile( $outdir, split( /::/, $1 ) ) . '.pm';

# its contents
$contents .= $_;
} elsif ( $_ =~ /^1;/g ) {

# put the contents into $filename
$contents .= $_;
my ( $volume, $directories, $file ) = File::Spec->splitpath($filename);

# make the path
mkpath(
$directories,
{
verbose => 1,
mode => 0711,
}
);
do {
open OUT, ">$filename" or die "Can't write to $filename: $!\n";
print OUT $contents;
close OUT;
} if $filename;
} else {
$contents .= $_;
}
}
close $fh;

3 comments:

szabgab said...

You could package it and upload to CPAN so it can become one of the refactoring tools use by Padre or EPIC if that is what you prefer.

szabgab said...
This comment has been removed by the author.
Ed said...

Post this script on CPAN? NOt sure if its worth that! Thanks for the flattery though!