Just a few comments on the code in general.

1) Why do you put '$banmask' into '%banmask' ? You aren't changing it anywhere, so this is pointless. Just use '$banmask'.

2) As this is a channel-based event, you can drop the '$chan' in the if tests, i.e. 'if ($me isop)'.

3) The if's look to be checking the same things a few times, so can be re-structured to not re-check so many times.

4) Unless you've got code after this, why are you doing an extra 'if' within the while? It's superflouous.