Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Reading (and parsing) a byte stream

by BrowserUk (Patriarch)
on Mar 05, 2006 at 04:06 UTC ( [id://534558]=note: print w/replies, xml ) Need Help??


in reply to Reading (and parsing) a byte stream

Take a look at the use of the '/' in the documentation for pack, you can also use this format character in unpack.

Basically, an unpack format of 'C/a', will read the byte value represented by the C, and then use that as the length specifier for the character following the '/'; in this case 'A' for ascii data. As you also need the length of the metadata in order to remove it from the stream, you'll need a template of "a$DATASIZE C X C/A", which will capture the data to the first variable, the length to the second, backup over the length byte and then use it to capture the metadata to the third variable.

I've used a datasize of 10 and an array to simulate the read in this example. The critical part is exiting the while loop when there is not enough data left to fulfill the data size, then read the next lump and append it to the residual:

#! perl -slw use strict; use bytes; my $DATASIZE = 10; my @stream = ( "abcdefghij\x04fredabcdefghij\x06barneyabcdefghij\x00abcde", "fghij\x07bam bamabcdefghij\x00abcdefghij" ); my $stream = ''; for ( @stream ) { $stream .= $_; while( length( $stream ) > $DATASIZE) { my( $data, $len, $meta ) = unpack "a$DATASIZE C X C/A", $strea +m; print "\ndata:$data"; print "meta:$meta" if $len; my $trim = $len ? $len+1 : 1; $stream = bytes::substr( $stream, $DATASIZE + $trim ); } } __END__ c:\test>junk data:abcdefghij meta:fred data:abcdefghij meta:barney data:abcdefghij data:abcdefghij meta:bam bam data:abcdefghij

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (8)
As of 2024-03-28 09:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found