title: Erlang: variable is unbound
body: <p>Why is the following saying variable unbound?</p>
  
  <pre><code>9&gt; {&lt;&lt;A:Length/binary, Rest/binary&gt;&gt;, Length} = {&lt;&lt;1,2,3,4,5&gt;&gt;, 3}.     
  * 1: variable 'Length' is unbound
  </code></pre>
  
  <p>It's pretty clear that <code>Length</code> should be 3.</p>
  
  <p>I am trying to have a function with similar pattern matching, ie.:</p>
  
  <pre><code>parse(&lt;&lt;Body:Length/binary, Rest/binary&gt;&gt;, Length) -&gt;
  </code></pre>
  
  <p>But if fails with the same reason. How can I achieve the pattern matching I want?</p>
  
  <hr>
  
  <p>What I am really trying to achieve is parse in incoming tcp stream packets as LTV(Length, Type, Value).</p>
  
  <p>At some point after I parse the the Length and the Type, I want to ready only up to <code>Length</code> number of bytes as the value, as the rest will probably be for the next LTV.</p>
  
  <p>So my <code>parse_value</code> function is like this:</p>
  
  <pre><code>parse_value(Value0, Left, Callback = {Module, Function},
         {length, Length, type, Type, value, Value1}) when byte_size(Value0) &gt;= Left -&gt;
      &lt;&lt;Value2:Left/binary, Rest/binary&gt;&gt; = Value0,
      Module:Function({length, Length, type, Type, value, lists:reverse([Value2 | Value1])}),
      if 
      Rest =:= &lt;&lt;&gt;&gt; -&gt;
          {?MODULE, parse, {}};
      true -&gt;
          parse(Rest, Callback, {})
      end;
  parse_value(Value0, Left, _, {length, Length, type, Type, value, Value1}) -&gt;
      {?MODULE, parse_value, Left - byte_size(Value0), {length, Length, type, Type, value, [Value0 | Value1]}}.
  </code></pre>
  
  <p>If I could do the pattern matching, I could break it up to something more pleasant to the eye.</p>