in reply to C idioms in Perl
The fact that the input format uses a fixed string "</TEMPLATE>" as a terminator allows for reading one record per input-operation. That way there is no need for line-assemblage to build up the hash value. Each round in the read loop processes one template.
In the code I'm using the DATA filehandle instead of opening the given file.
Note the slight modification in the name-extracting regex. I have made it match trailing whitespace, so that the index $+[0] (for @- and @+ see perlvar) points to the first valid character of the template text.sub read_template { my ($templfile, $hashref) = @_; my $fh = \ *DATA; # by way of open(...) local $/ = '</TEMPLATE>'; # set the record terminator while ( <$fh> ) { last if /^\s*$/; # ignore trailing newline(s) chomp; # remove trailing terminator my ( $name) = /^\s*<\s*TEMPLATE\s+NAME="(.*)"\s*>\s*/i or die "data error in $templfile, chunk $."; $hashref->{ $name} = substr( $_, $+[ 0]); } } __DATA__ <TEMPLATE NAME="TEMPLATE1"> # Processing instructions here ... </TEMPLATE> <TEMPLATE NAME="TEMPLATE2"> # Instructions for some other action ... </TEMPLATE>
Anno
|
---|