That seems a very clumsy way of parsing to me. You're having to re-parse the same information multiple times. And the number of times will only grow as you add more cases.
A given/when or if/elsif/.../else cascade seems far more appropriate:
#!/usr/bin/perl
use strict;
use warnings;
my $content;
my $error;
while( <DATA> ) {
unless( s[^#include (.+)$][] ) {
chomp;
warn "Non-include line '$_' untouched\n";
$content .= $_ . "\n";
}
else{
local $_ = $1;
if( m[<math] ) {
$content .= qq[import java.lang.Math;\n];
}
elsif( m["stdafx.h"] ) {
$content .= qq[#include "stdafx"\n];
}
elsif( m["(.+)"] ) {
open my $inc_handle, '<', $1
or warn "$1: $^E\n" and ++$error and next;
local $/; # slurp
$content .= <$inc_handle> . "\n";
}
else {
warn "Unhandled include $_\n";
$error++;
}
}
}
print "\nContent:\n'$content'\n";
die "$error errors encountered\n" if $error;
__DATA__
#include "stdafx.h"
#include <math.h>
#include <stdio.h>
// A comment
#include "AlyLee.h"
#include "Common.h"
Produces: C:\test>junk49
Unhandled include <stdio.h>
Non-include line '// A comment' untouched
AlyLee.h: The system cannot find the file specified
Common.h: The system cannot find the file specified
Content:
'#include "stdafx"
import java.lang.Math;
// A comment
'
3 errors encountered
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
|