in reply to Avoid run-time checking

Hello bagyi,

This sounds like a textbook example of a problem waiting for an OO solution. Make a Record class containing a factory-pattern constructor along with the various methods applicable to a record. Then create a subclass for each record type — e.g. Record_Big_Endian and Record_Little_Endian — which inherit from the parent Record class. Override Record methods in these subclasses if and when necessary. This will give you an API which can be used without explicit reference to the endianness of the records being processed:

use Record; ... my $endianness = get_first_record($file); # or better: put this into + the Record::new class method my $record = Record::new($endianness); # returns either a Record_ +Little_Endian or a Record_Big_Endian object $record->unpack(); # unpacks the record in a +way that is endian-transparent ...

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Avoid run-time checking
by bagyi (Acolyte) on Sep 12, 2015 at 08:30 UTC
    Hi Athanasius,

    OO approach looks over-kill to me. since unpacking template is only a small part of parsing a record.

    Refactoring this into two different classes would be creating more duplication of code. since the rest of logic is the same.(handling missing field, and what not..;)

      Refactoring this into two different classes would be creating more duplication of code. since the rest of logic is the same.(handling missing field, and what not..;)

      So make 3 classes , they don't have to OO :) MyRecs; MyRecs::Big; MyRecs::Lil;

      sub MyRecs::foo { my( $ro, $sham, $bo ) = @_; die "sham must sham " if not $sham =~ /sham/i; ... } sub MyRecs::Lil::foo { MyRecs::foo( unpack "n3A*", ... ); } sub MyRecs::Big::foo { MyRecs::foo( unpack "v3A*", ... ); }