How to set variable at the head of a context

I want to set a variable at the start of a context, regardless of the extension dialed. (My PBX is using two-digit extensions.) I tried:

[mycontext]
exten = _X.,1,Set(MYVAR=123)
exten = _XX,1,Goto(anotherplace,1)
include = othercontext

[othercontext]
exten = anotherplace,1,...

I thought it would match the first line, set the variable, and then match the second, but as you all know that doesn’t work because the pattern match sort matches on _XX first and it goes right to [othercontext] without setting the variable. I read that “include” statements effectively break up the pattern sorting, so I tried this:

[mycontext]
exten = _X.,1,Set(MYVAR=123)
include = mycontext_part_two

[mycontext_part_two]
exten = _XX,1,Goto(anotherplace,1)
include = othercontext

[othercontext]
exten = anotherplace,1,...

…my expectation was that it would set the variable, and then match on the exten = _XX inside mycontext_part_two. Instead it set the variables as expected, and then went right to Hangup.

Is there a better way to create an “always do <something> at the start of a context”?

Regardless, what am I misunderstanding about the dialplan flow here?

Thanks!

Oh, hmm… is it the case that asterisk only executes a single extension in a given context?

I was thrown by this documentation, which says “Asterisk doesn’t stop processing the dialplan after the first matching extension is found”, and gives an example where it matches on 6001, and then later matches on _., which made me think it would fall through as I expected in my post above?

Asterisk uses the best match extension for each priority in the context, and continues until an application returns a non-zero result, there is no match for the extension, or there is a control transfer, changing the next priority. Your _XX. line is a better match than your _X. line.

Whilst you could have _X. for priority 1, then the specific extensions for priority 2, that would mean all extensions (starting with a digit) were treated as existing, which might break some things.