benmmurphy
benmmurphy

Reputation: 2505

Match Last Byte of a Binary in a Guard

Is it possible to match the last byte in a binary using pattern matching. Something like:

<<Rest/binary, 45>> = BinaryToMatch 

Upvotes: 0

Views: 1545

Answers (3)

Val Tikhonov
Val Tikhonov

Reputation: 31

In erlang 19 (may be previous versions also support this, I don't test them) you can use this guard :

when binary_part(Key, {byte_size(Key), -1}) =:= BinMatchElement

Upvotes: 2

nox
nox

Reputation: 471

Alternatively, you can also do 45 = binary:last(Bin). Unfortunately this function is not a guard BIF.

Upvotes: 2

YOUR ARGUMENT IS VALID
YOUR ARGUMENT IS VALID

Reputation: 2059

In short, no (at least not in R14B01). You must also know the size of the binary.

Skip = byte_size(BinaryToMatch) - 1,
<<_:Skip/binary, 45>> = BinaryToMatch.

Upvotes: 4

Related Questions