[erlang-questions] Binary pattern matching inconsistencies with R12B

Rory Byrne rory@REDACTED
Fri Feb 29 23:04:31 CET 2008


On Fri, Feb 29, 2008 at 01:00:29PM -0500, Rusty Klophaus wrote:
> 
> You may want to try specifying a size for the variables D, N, and C.
> 
> For example: scan(<<C:8/integer, Rest/binary>>, TokAcc)
> 
> According to the manual: "In matching, this default value is only valid  
> for the very last element. All other bit string or binary elements in the  
> matching must have a size specification."  
> (otp_doc_html_R12B-1/doc/reference_manual/expressions.html#6.16)
> 
> It's possible that the lack of a size is confusing things.
> 
> Hope that helps,

Cheers Rusty, I took a shot at that, but no dice I'm afraid.

Actually, I ran into a problem on another project that led me to
this passage last week. I was trying to write something like

    <<Data/binary, Pad:8>> = Payload.

but the compiler was complaing (as compilers do). What it was 
trying to tell me was that a binary type must have a length 
field unless it appears at the end of a <<binary>> pattern.
Sorry, when speaking about this stuff the term binary inevitably
gets overloaded. In essence, it was telling me I had to 
do something like:

    Length = size(Payload) - 1,
    <<Data:(Length)/binary, Pad:8>> = Payload.

Something like that anyway. That's what the passage you quoted is
about - it's talking about using the binary type within a pattern.
You must specify a length with it unless it's at the end of the 
pattern.

Also, the defaults for items in a pattern are size 8 and type
integer - so I think my code is safe. Truth be told, if I 
had to write that stuff for each term I'd probably just convert
the thing to a list and do matching that way. Yeah, I'm that
lazy :-)

Thanks again Rusty, 

Rory




More information about the erlang-questions mailing list