Splitting Fortran Files into Subroutines

Coding in fortran, I often find it easier to work with numerous files each containing a single subroutine.  This can make it easier to compare two versions of files in which order of subroutines may have changed (since each subroutine is compared instead of the files all at once), it makes compiling faster as less code needs to be recompiled on every edit, it makes it easier to use a text editor, since you can see a greater fraction of the file at once.  It’s not all good though, sometimes it’s nice to have subroutine clustered together in a module.  But on the whole, I’d rather deal with 100 duck sized horses.  So the question is then, how can I quickly and easily go from one giganto file to many one subroutine files.  Answer, a couple of options:

1) f77split – This was probably the first one I tried, works pretty well.

2) f90split – For newer fortran.

3) Homebrewed: Fair warning, haven’t used this in a little bit, but it was useful the last time I did, and I believe this is the most recent version.  Also, it’s not pretty, it’s not really supposed to be.  It’s supposed to accomplish a fairly simple task as simply and with as little effort as possible while being theoretically simple.

#!/usr/bin/perl
use strict;

my $filename = $ARGV[0];
chomp($filename);
my $basename = $filename;
$basename =~ s/(.*)\..*/$1/; # chop off until the end of the line

system("mkdir -p $basename"); # make the file for one
my $current_subroutine_title = '';
my $file_open = 0;

open SOURCEFILE, "<", "$filename" or die $!;

while(my $fileline = )
{
chomp($fileline);
# print "$fileline\n";
if($fileline =~ m/^\s+subroutine\s+(\w+)/i)
{
print "now reading subroutine $1\n";
if($file_open > 0){close(SUBROUTINEFILE);}
open SUBROUTINEFILE, ">", "$basename/$1.F" or die $!;
$file_open = 1;
}
if($file_open > 0)
{
print SUBROUTINEFILE "$fileline\n";
}
}

if($file_open > 0){close(SUBROUTINEFILE);}
close(SOURCEFILE);

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

%d bloggers like this: