So, since I do not know for sure I will just put this as a comment.
Perish song affects the active pokemon on from all trainers in the battle. The only way to avoid it is by switching out. Since you were on your last mon, perish song cannot be avoided by you switching. In your case though you had swept all of his pokemon while the perish song counter was going down. My guess as to why you take the loss in this scenario is because it is possible that Perish song counter goes down after your turn is done.
So, as soon as you confirm your attack the counter goes down, because your turn is over as soon as you choose your move, taking priority over anything that happens after the attack itself. Thus making you lose even though you had taken out his final mon. The order of which events occur may happen due to priority of the moves/abilities. I am not sure if this is how it works, but I will see what I can find.