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

Re: unpack less than indicated length

by hexcoder (Curate)
on Jun 03, 2018 at 18:54 UTC ( [id://1215792]=note: print w/replies, xml ) Need Help??


in reply to unpack less than indicated length

Hello paulrh,

you can do it like this:
(a) first splitting the input string into complete records with (xCXX /A)*, (this skips the type, reads the length byte, goes back 2 bytes, and uses the length to read the record)
(b) then for each record extract type and string map { unpack "CxA*", $_ } (this reads the type, skips the length byte, and reads the string of the record).

use strict; use warnings; my $inputString = "\x03\x04Hi\x43\x08Hello!"; my %myDict = map { unpack "CxA*", $_ } unpack "(xCXX /A)*", $inputStri +ng; print "$myDict{0x03}\n"; # "Hi" print "$myDict{0x43}\n"; # "Hello!"

[edit]
better wording: chopping -> splitting
Your code created an extra entry in the hash (type = 0x30, empty string) because of the appended "00".
[edit2]
Incorporated the hint from AnomalousMonk (thanks!)

Replies are listed 'Best First'.
Re^2: unpack less than indicated length
by AnomalousMonk (Archbishop) on Jun 03, 2018 at 19:45 UTC
    my %myDict = map { unpack "CxA*" } unpack "(xCXX /A)*", $inputString;

    NB: unpack TEMPLATE only unpacks the default scalar  $_ with Perl versions 5.10 and above. Prior to 5.10, use
        my %myDict = map { unpack "CxA*", $_ } unpack "(xCXX /A)*", $inputString;


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-03-28 20:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found