I've recently been assisting a colleague with some legacy code at work, and I came across the attached function, which I think is attempt to rewrite a C idiom into Perl.
By way of context, this function takes as arguments the name of a template file and a reference to a hash. The content of the template file is a set of pseudo-HTML template definitions, which are parsed out by this function and stored in the hashref.
Templates follow the pattern:
<TEMPLATE NAME="TEMPLATE1"> # Processing instructions here ... </TEMPLATE> <TEMPLATE NAME="TEMPLATE2"> # Instructions for some other action ... </TEMPLATE> # etc
The exact form of the processing instructions is irrelevant, as they are simply copied into the hash (as we shall see).
The subroutine is shown below (with error checking and some irrelevant detail removed for clarity):
sub read_template { my ($templfile, $hashref) = @_; my ($line, $dest, $stuff); my $fh = new FileHandle("<$templfile"); # This looks like a C idiom. # $dest is initially set to point to $stuff (which is # undef). # # If a template start is found, the hash key is set with # the template name, and # $dest is re-pointed at the value corresponding to this # hash key. # # Subsequent lines are appended to $dest (and hence to # the hash value), # until a closing tag is found, at which point $dest is # re-set to $stuff again. # # The hash is a reference, so we are also modifying the # caller at the same time. Nothing is explicitly # returned. # $dest = \$stuff; while ($line = <$fh>) { if ($line =~ /^\s*<\s*TEMPLATE\s+NAME="(.*)"\s*>/i) { $hashref->{$1} = ''; $dest = \$hashref->{$1}; } elsif ($line =~ /^\s*<\s*\/\s*TEMPLATE\s*>/i) { $dest = \$stuff; } else { ${ $dest } .= $line; } } $fh->close; }
My questions are these:
In reply to C idioms in Perl by slife
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |