The team known as 'the yellow submarine', who are 17th, moved seven points clear of the bottom three on to 35 points with six left to play.
Villarreal finished fourth last term and started the campaign in the Champions League [ Images ], but suffered a dramatic loss of form and are now on their third coach this season in Miguel Angel Lotina as they seek to avoid the drop.
Their Paraguayan midfielder Perez struck a dipping volley from outside the area in the 94th-minute to secure the points, as they made the most of the sending off of Malaga keeper Carlos Kameni in the 81st minute.
The Cameroon stopper was shown a straight red card after he brought down Perez in the area, and Marcos Senna netted the equaliser from the spot.
Spanish international Santi Cazorla, a central figure at Villarreal when they secured a top-four finish last year, had opened the scoring for Malaga in the 65th minute and refused to celebrate his goal out of respect for his former supporters.
Malaga, who are owned by a member of the Qatari royal family, stayed fourth with 50 points and missed out on the chance to reclaim third place from Valencia on 52. Valencia hammered Rayo Vallecano 4-1 on Wednesday.
Leaders Real Madrid [ Images ] edged closer to their first league title in four years with a 4-1 derby victory at Atletico Madrid on Wednesday which put them on to 82 points, four ahead of Barcelona [ Images ] in second.
Sevilla climbed to seventh with 45 points after a 3-0 win over Real Zaragoza.
Racing Santander's plummet towards the second division continued when they lost 3-0 at home to Real Mallorca [ Images ], conceding the first goal to Emilio Nsue after around 20 seconds. They have taken only one point from their last eight games.
The north-coast club, who are in administration, stayed bottom with 25 points, three behind Sporting Gijon in 19th and Zaragoza in 18th.