Anto Joy
Anto Joy

Reputation: 135

Erlang - Why cant I use size() of a value when pattern matching a binary?

Assigned values,

A = <<"hell">>

I have two code snippets which should do the same operation,

<<A:size(A)/binary, Rest/binary>> = <<"hello">>

The above fails with the reason : syntax error before: '('

Then I assign value of size(A) to B,

B = size(A)

Then the following snippet works,

<<A:B/binary, Rest/binary>> = <<"hello">>

Why wont the first work?

Upvotes: 1

Views: 115

Answers (1)

Hynek -Pichi- Vychodil
Hynek -Pichi- Vychodil

Reputation: 26141

According to Reference Manual 8.17 Bit Syntax Expressions

Used in a bit string construction, Size is an expression that is to evaluate to an integer.

Used in a bit string matching, Size must be an integer, or a variable bound to an integer.

So even <<A:(size(A))/binary, Rest/binary>> = <<"hello">> would be correct syntax, it is not allowed in matching (illegal bit size).

Upvotes: 1

Related Questions