Binary guards problem

Bjorn Gustavsson <>
Mon Oct 23 15:15:38 CEST 2000


Luke Gorrie <> writes:

> Bjorn Gustavsson <> writes:
> 
> > Yes, I would like to see the code that reproduces the error.
> 
> Here is a better example:
> 
>   Eshell V5.0.1  (abort with ^G)
>   1> A = <<1, 2, 3>>.
>   <<1,2,3>>
>   2> B = <<4, 5, 6>>.
>   <<4,5,6>>
>   3> <<A, B>> = <<1, 2, 3, 4, 5, 6>>.
>   ** exited: {{badmatch,<<1,2,3,4,5,6>>},[{erl_eval,expr,3}]} **

Equvivalent to

	<<A:8/integer, B:8/integer>> = <<1, 2, 3, 4, 5, 6>>

>   4> <<A/binary, B/binary>> = <<1, 2, 3, 4, 5, 6>>.
>   ** exited: {{badmatch,<<1,2,3,4,5,6>>},[{erl_eval,expr,3}]} **

If you would have used unbound variables, you would have got:

    A = <<1, 2, 3, 4, 5, 6>>
    B = <<>>

Since A and B were bound, what will be matched is

	<<1, 2, 3>> = <<1, 2, 3, 4, 5, 6>>

You must write

	Sz = size(A).

	<<A:Sz/binary, B/binary>> = <<1,2,3,4,5,6>>.

to get the result you want.

>   5> <<A/binary, B/binary>> == <<1, 2, 3, 4, 5, 6>>.
>   true
> 

/Björn
-- 
Björn Gustavsson            Ericsson Utvecklings AB
      ÄT2/UAB/F/P
			    BOX 1505
+46 8 727 56 87 	    125 25 Älvsjö



More information about the erlang-questions mailing list