in reply to Re^7: while(){}continue{}; Useful?
in thread while(){}continue{}; Useful?
As best as I can tell, you either need a recursive parser to handle the new material or need to add new material to the existing work queue.
Turning what I had into a recursive parser is trivial and probably more robust:
#!/usr/bin/perl use strict; use warnings; my $error; sub parse { my $fh = shift; my $content = ''; while( <$fh> ) { 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; $content .= parse( $inc_handle ); } else { warn "Unhandled include $_\n"; $error++; } } } return $content; } my $content = parse( \*DATA ); 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"
I also added some handling for #pragma once and discovered I'll have to handle some nested #ifdefs.
And I think a recursive parser is the only way to go if your going to start handling conditionals.
And you're going to have to get a lot more sophisticated. You'll need to start storing state--the current values of #defines etc.--in order that you can decide which branch of #ifdef #else to process, which may determine which includes you need to process. And at that point, logging and error and trying to continue for missing files doesn't work at all. The only thing you can do is die.
As an example of the use of continue, it doesn't really hold up for me. If all your if blocks have to next to avoid entering the continue anyway, you might as well just stick the error handling at the bottom of the while. But as your code above shows, the idea that you can handle all the possible errors in one place doesn't hold up either.
If this is a serious project, then you'd almost certainly be better off using an existing pre-processor like m4. Or cl/gcc -E.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^9: while(){}continue{}; Useful?
by kennethk (Abbot) on Apr 06, 2010 at 14:55 UTC |