Chasing a target of 244 to win, Pakistan required 68 runs from 60 deliveries when Perera came on to bowl the 41st over. He dismissed Younis Khan, Shahid Afridi and Sarfraz Ahmed in successive deliveries for the 32nd hat trick in ODI cricket, and he then produced a run out with a direct hit on the following delivery to restrict Pakistan to 176-8 after being 176-4 earlier in the over.
Perera finished with 4-42 and was named man of the match after Pakistan lost its first match at R. Premadasa Stadium in eight years, having previously won eight with two ending in a no-result due to inclement weather.
A 130-run stand between captain Misbah-ul-Haq and Azhar Ali took Pakistan to 166-2 by the 37th over. But the Sri Lankans caught and fielded well, an area in which Pakistan made plenty of mistakes, to claim the last eight wickets for 33 runs.
Earlier, Sangakkara's innings on a slow pitch led Sri Lanka to 243-8, missing out on what would have been his first century at home in eight years when Azhar Ali ran from deep mid-wicket and took a diving catch of Saeed Ajmal. Sangakkara was given out after the on-field umpires referred third umpire to rule whether the catch had been taken cleanly.
Sangakkara hit seven fours and three sixes in 130 balls, putting on 110 from 109 deliveries with Mahela Jayawardene, who made 40 off 50 deliveries with four fours.
Sangakkara was slow off the blocks after Sri Lanka elected to bat and was dropped on 35 by Umar Gul at long-on. He needed 99 deliveries to reach his half-century, but was soon striking the ball sweetly.
Sri Lanka opted for the batting power play in the 36th over and the fielding restrictions helped the batsmen to score 49 without losing a wicket. Gul paid for giving Sangakkara a life, the batsman hooking him for a six before lofting another ball into the stands behind long-on.
The last match in the series is on Monday.