Text::Balanced is now a standard Perl 5.8.0 module, which seems
a good thing to me (though I have not used it before). Anyway, it
seems a handy tool for a chore I have parsing a configuration file.
I suppose I might use a bigger Parse::RecDescent hammer for this job,
or do it in some other way. Which is why I am asking for comments on
my approach below (an incomplete first cut at the problem). For this
particular problem, I can assume that the configuration file is
syntactically correct (though proper error detection and reporting
is an interesting problem that I may face in the future).
Better/alternative approaches to solving this problem are welcome.
(If anyone knows of a more appropriate list to post this problem,
please let me know).
/-\
use strict;
use Text::Balanced qw(extract_bracketed);
my $tt_in = <<'FLAMING_OSTRICHES';
! this is a comment line (comments not allowed at end of statements)
! there should be only one SUBSYS line as first 'statement'
SUBSYS GROUPS
!next two lines is a statement (comments not allowed in statements)
NODES ( "this is a description, ignore next bracket )",
'( test', HW = 2 and (OS = 2 or (OS > 5 and OS < 11)) )
! statements can span multiple lines and are ended when matching
! bracket is found
KNOBS ("knob", FRED, 'hello world' )
! last comment
FLAMING_OSTRICHES
print "in ='$tt_in'\n";
my $subsys_sg = 'GROUPS';
my $tt_out = "";
my @r;
my $n_subsys = 0;
{
if ($tt_in =~ /\G([ \t]*\n)/gc)
{
print "blank line d1='$1'\n";
$tt_out .= $1;
}
elsif ($tt_in =~ /\G([ \t]*!.*\n)/gc)
{
print "comment line d1='$1'\n";
$tt_out .= $1;
}
elsif ($tt_in =~ /\G([ \t]*SUBSYS[ \t]+$subsys_sg[ \t]*\n)/iogc)
{
print "subsys line d1='$1'\n";
$tt_out .= $1;
++$n_subsys;
}
elsif ((@r=extract_bracketed($tt_in,'(\'")','[ \t]*\w+[ \t]+'))[0])
{
my $k = $r[2]; $k =~ tr/ \t//d;
print "bracketed k='$k' d1='$r[0]'\n";
# More work to do here to analyse statement $k
$tt_out .= $r[2] . $r[0];
}
else
{
last;
}
redo;
}
print "out='$tt_out'\n";
http://www.yahoo.promo.com.au/hint/ - Yahoo! Hint Dropper
- Avoid getting hideous gifts this Christmas with Yahoo! Hint Dropper!