I was thinking about how "pain" could be used as a programming concept. Found the answer in
Homeostasis and soft robotics in the design of feeling machines
by Kingson Man and Antonio Damasio
They say that feelings are the response to a system being out of equilibrium.
So then a good answer to my question is to allow every subroutine of a "system" to be passed a pointer to its "environment", as well as pointers to other "neighboring" system subroutine's state, and have an automatic mechanism for comparing the curret subroutine's internal state to this environment and neighbors, to come up with a vector of disturbance from equilibrium. Each subroutine can then take exactly the same form as a 'switch' statement on the values of the disturbance vector. Pain would then be considered to be some of the case statements within this 'switch'. In a simple version, the disturbance is a real valued number and pain is a threshold that affects the subroutine's behavior.
Note in passing that a system would simply move towards death, if all that mattered was equilibrium. There needs to be a larger "equilibrium" driving a system out of local equilibrium, if the system is to do any work. For better or worse, such ideas lead the conversation forward and connect "pain" in a useful way to other programming constructs.