rodion has asked for the wisdom of the Perl Monks concerning the following question:
my %test_vals; @test_vals{ @TEST_FLD } = unpack $TEST_REC_PACK, $rec;
to load up the test_vals hash . Below is our first pass on specifying the two constants needed, $TEST_REC_PACK and @TEST_FLD.
I've looked at Data::FixedFormat, Text::FixedLength and Parse::FixedLength to see if they would simplify things, but they don't appear offer enough to justify the mental overhead of having to refer to documentation in a separate module. Initially at least, plain old Perl looks clearer.
Update: Note that the correspondence with the fat commas, "=>" is loading an array, rather than a hash. This is so that the field specs and field names are available in order. A hash would lose this order.
I have two questions, at different levels, about our first pass approach below.
Your considered wisdom, advice and opinions are much appreciated.
Testing Code:my @TEST_FLD = (); my $TEST_REC_PACK = q{}; my @TEST_REC_PACK_FLDS = ( status => 'n ', # 0 time => 'n ', # 2 date => 'N ', # 4 code => 'a16', # 8 key msid => 'a10', # 24 key); my $TEST_REC_LEN = 34; # split pack-spec & fld names (one-line-ish) my $odd=0; ($odd^=1) ? push @TEST_FLD,$_ : ($TEST_REC_PACK.=$_) for (@TEST_REC_PACK_FLDS); # split pack-spec & fld names (using a sub) ($TEST_REC_PACK,@TEST_FLD) = Split_pack_flds_spec(@TEST_REC_PACK_FLDS); sub Split_pack_flds_spec { my $spec; my @fld; my $odd = 0; for (@_) { if ($odd = !$odd) { push @fld,$_; } else { $spec .= $_; } } return ($spec,@fld); }
print 'fields = (',join(',',@TEST_FLD),")\n"; print "pack spec = \"$TEST_REC_PACK\"\n"; my $rec = "\x{00}\x{7B}\x{06}\x{B3}\x{01}\x{32}\x{1A}\x{83}" .'code_value------msid_value'; my %test_vals; @test_vals{ @TEST_FLD } = unpack $TEST_REC_PACK, $rec; my ($key,$val); while (($key,$val)=each(%test_vals)) { printf " %6s => %s\n",$key,$val; }
|
|---|