I agree that the use of a scalar reference to keep track of a hash value looks like a something a C programmer would do. In general, scalar references are rarely used in Perl (they do have their place). In this case, knowing the hash(ref) and the key is good enough. Declaring all the variables near the beginning of a sub is another C-ism. Most of the time it is possible, and preferrable, to declare variables where they are first used.

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.

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>
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.

Anno


In reply to Re: C idioms in Perl by Anno
in thread C idioms in Perl by slife

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.