Thank you so much for your reply!
I tried running the code you posted with perltex, but it gives the following errors
(1)Undefined control sequence
(2)end occured inside a group at level 3.
This is probably some stupid mistake, but I just can't figure it out.