我有一个文件,其中包含 n 个子例程定义,如下所示(每个例程都以sub
关键字开头和结尾bar
):
sub foo()
contents
bar
sub good ()
contents
bar
sub right ()
contents
bar
我想创建三个名为 的文件foo.s
,good.s
并将right.s
各自的子例程写入相应的文件中。我尝试了以下脚本,但由于我对 Perl 脚本完全陌生,因此对全局/局部变量进行了不当管理。我怎样才能做到这一点?
my $op = 0;
my $fnamet = $ARGV[0];
if(not defined $fnamet) {
die "Top file name not known\n";
}
my $srcfile = "source/$fnamet.s";
print "$srcfile\n";
open (SRC, $srcfile) or die "Couldn't find source file\n";
foreach $line (<SRC>) {
if ($op == 0) {
strtwrite($line, $op);
} elsif ($op == 1) {
stopwrite($line, $op);
}
}
if ($op == 1) {
print "Some sub is missing bar statement or having\n";
print "additional sub statement";
close (DST);
}
close (SRC);
}
sub strtwrite {
unless ($_[0] =~ /^\s*sub\s*.*/) {
print "Searching for a sub start\n";
$op = 0;
} else {
print "A sub start found\n";
print "$_[0]\n";
my @temp = (split /[\s,();]+/, $_[0]);
my $strt = '';
if($temp[1] =~ 'sub') {
print "Comparing with sub pass \n";
$strt = $temp[2];
} else {
print "Comparing with sub fail \n";
$strt = $temp[1];
}
my $fnameb = "dstcodes/$strt.s";
print "\n\n $fnameb \n\n";
open (DST, '>$fnameb') or die "Couldn't open sub file\n";
print DST $_[0];
$op = 1;
}
}
sub stopwrite {
unless ($_[0] =~ /^\s*bar\s*.*/) {
# Copy till the bar is found
print "Searching for an bar\n";
print DST $_[0];
$op = 1;
} else {
# Close the current destination file and start waiting
# for next SUB start
print "A matching BAR found\n";
print DST $_[0];
close (DST);
$op = 0;
}
}