in reply to Weird syntax. What does this goto statement do?
A simple state machine (with information missing):
INITIAL_STATE SOME_STATE FINAL_STATE +-----+ +-----+ +-----+ start--->| |---+--->| |------->| |--->accept +-----+ | +-----+ +-----+ | | +-------+
We can imagine a state machine as a bunch of gotos.
We could replace those gotos with sub calls.INITIAL_STATE: { ... goto SOME_STATE; } SOME_STATE: { ... if ( ... ) { goto SOME_STATE; } else { goto FINAL_STATE; } } FINAL_STATE: { ... }
sub initial_state { ... return some_state(); } sub some_state { ... if ( ... ) { return some_state(); } else { return final_state() } } sub final_state { ... return; } initial_state();
The stack will keep growing and growing unless we perform tail call elimination, which can be done using goto &SUB
sub initial_state { ... goto &some_state; } sub some_state { ... if ( ... ) { goto &some_state; } else { goto &final_state; } } sub final_state { ... return; } initial_state();
This is the approach used by the code in question. goto &sub is slow, though. (Slower than a sub call.) I think we could use a loop to speed things up.
sub initial_state { ... return \&some_state; } sub some_state { ... if ( ... ) { return \&some_state; } else { return \&final_state; } } sub final_state { ... return undef; } my $state = \&initial_state; while ( $state ) { $state = $state->(); }
The code in question appears to have some code place to support this. It "returns" the new handler sub (by assigning it to $_[0]->{state}), but it never ends up using it.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Weird syntax. What does this goto statement do?
by LanX (Saint) on Jan 04, 2024 at 00:32 UTC | |
by ikegami (Patriarch) on Jan 04, 2024 at 15:01 UTC |