Regular expressions like it's still 1998. If I may:
use warnings;
use strict;
use Regexp::Grammars;
use Data::Dumper;
my $data = join "", <DATA>;
my $matcher = qr{
<debug: off>
<nocontext:>
^
<Module>
<[Commands]>+
<EndModule>
$
<token: Module>
module \s <Name> \s <BracketedNodes>; \n
<token: EndModule>
endmodule \n?
<token: Commands>
( <Input>|<Output>|<Wire>|<Nand> );\n
<token: Nand>
nand \s <Name> \s <BracketedNodes>
<token: Input>
input \s <Nodes>
<token: Output>
output \s <Nodes>
<token: Wire>
wire \s <Nodes>
<token: Name>
[\p{L}\d_]+
<token: Node>
N\d+
<token: Nodes>
<[Node]>+ % ,
<token: BracketedNodes>
\(<Nodes>\)
};
if ( $data =~ $matcher )
{
print Dumper \%/; #/
}
else
{
print "NO MATCH";
}
__DATA__
module circuit_17 (N1,N2,N3,N6,N7,N22,N23);
input N1,N2,N3,N6,N7;
output N22,N23;
wire N10,N11,N16,N19;
nand nand2_1 (N10,N1,N3);
nand nand2_2 (N11,N3,N6);
nand nand2_3 (N16,N11,N2);
nand nand2_4 (N19,N11,N7);
nand nand2_5 (N22,N10,N16);
nand nand2_6 (N23,N16,N19);
endmodule
Yields
$VAR1 = {
'Module' => {
'BracketedNodes' => {
'Nodes' => {
'Node' => [
+ 'N1',
+ 'N2',
+ 'N3',
+ 'N6',
+ 'N7',
+ 'N22',
+ 'N23'
]
}
},
'Name' => 'circuit_17'
},
'Commands' => [
{
'Input' => {
'Nodes' => {
'Node' => [
'N1'
+,
'N2'
+,
'N3'
+,
'N6'
+,
'N7'
]
}
}
},
{
'Output' => {
'Nodes' => {
'Node' => [
'N2
+2',
'N2
+3'
]
}
}
},
{
'Wire' => {
'Nodes' => {
'Node' => [
'N10'
+,
'N11'
+,
'N16'
+,
'N19'
]
}
}
},
{
'Nand' => {
'BracketedNodes' => {
'Nodes'
+=> {
+ 'Node' => [
+ 'N10',
+ 'N1',
+ 'N3'
+ ]
+ }
},
'Name' => 'nand2_1'
}
},
{
'Nand' => {
'Name' => 'nand2_2',
'BracketedNodes' => {
'Nodes'
+=> {
+ 'Node' => [
+ 'N11',
+ 'N3',
+ 'N6'
+ ]
+ }
}
}
},
{
'Nand' => {
'Name' => 'nand2_3',
'BracketedNodes' => {
'Nodes'
+=> {
+ 'Node' => [
+ 'N16',
+ 'N11',
+ 'N2'
+ ]
+ }
}
}
},
{
'Nand' => {
'Name' => 'nand2_4',
'BracketedNodes' => {
'Nodes'
+=> {
+ 'Node' => [
+ 'N19',
+ 'N11',
+ 'N7'
+ ]
+ }
}
}
},
{
'Nand' => {
'BracketedNodes' => {
'Nodes'
+=> {
+ 'Node' => [
+ 'N22',
+ 'N10',
+ 'N16'
+ ]
+ }
},
'Name' => 'nand2_5'
}
},
{
'Nand' => {
'Name' => 'nand2_6',
'BracketedNodes' => {
'Nodes'
+=> {
+ 'Node' => [
+ 'N23',
+ 'N16',
+ 'N19'
+ ]
+ }
}
}
}
],
'EndModule' => 'endmodule'
};
Now for sanity checking you can inspect the result hash, but malformed data will simply not match the regex. If you want useful error messages you can add callbacks to the grammar.
holli
You can lead your users to water, but alas, you cannot drown them.