Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: C idioms in Perl

by Anno (Deacon)
on Sep 05, 2007 at 23:18 UTC ( [id://637289]=note: print w/replies, xml ) Need Help??


in reply to C idioms in Perl

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://637289]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (4)
As of 2024-04-26 01:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found