Tags Perl

In an effort to adapt my Perl data-decoding program to more needs, I'm now doing some major adjustments, including entirely configurable frame formats read in from a .xml configuration file.

The following issue arised: how do I efficiently store how to parse fields from a frame in the XML and what internal format is best for storing this information ? Well, why not store subroutines that are created using the information read from the .xml - for each field, a subroutine is provided which takes a frame and returns the field value from the frame.

Soon enough I found out that it's not a new idea. There's in fact an example of something similar in the Advanced Perl Programming book (1st edition) - extracting columns for text. Though my need is a bit more complex (I have to store these subroutines in hashes for later), it's basically the same thing.

What's best is that this method is even more efficient, as the subroutines are custom-tailored for every field and do their work without extra lookups.

Such things are done in Perl using eval with a judicious usage of the various quotes (the difference between ' and " really becomes crystal clear).

# create a subroutine reference
my $subref = sub {return 2;};

# same thing
my $subref2 = eval 'sub {return 2;}';

# now, something more interesting
my $val = 2;
my $subref3 = eval "sub {return $val;}";

Although in Lisp doing such things is much easier (Lisp includes special operators to generate code on-the-fly), it's not that bad in Perl, really. In stricter languages like C and C++ this is, of course, impossible.

All in all, it's a very nice solution, using powerful programming techniques for elegant and efficient code.


comments powered by Disqus