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, 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 goalkeeper 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.
"It's a very important win for us, it removes a great weight," Lotina told reporters.
"It was a win against one of the most in-form teams, in the Champions League places, and the heroic manner of the victory helps get the fans behind us more."
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 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 in second.
Sevilla climbed to seventh with 45 points after a 3-0 win over Real Zaragoza.
Two players on the fringes of the Spain squad, Alvaro Negredo and Jesus Navas, put in performances which would have boosted their chances of making Vicente del Bosque's team for Euro 2012.
Federico Fazio headed Sevilla's opener from a corner and striker Negredo burst through the middle to score the second after 29 minutes.
Winger Navas was a constant threat down the right flank and crossed for Negredo to stoop and head his second, to complete the scoring just before half-time.
Racing Santander's plummet towards the second division continued when they lost 3-0 at home to Real Mallorca, 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.
Get the best features, fun and footballing frolics straight to your inbox every week.
Thank you for signing up to Four Four Two. You will receive a verification email shortly.
There was a problem. Please refresh the page and try again.