Securities clearing and settlement is a complex topic - you can start by browsing relevant Wikipedia articles, and (given sufficient quantities of masochism and strong coffee) progress to entire technical books.
You're correct - modern trade settlement systems are electronic and heavily streamlined. However, you're never going to see people hand over assets until they're sure that payment has cleared - given current payment systems, that means the fastest settlement time is going to be the next business day (so-called T+1 settlement), which is what's seen for heavily standardized instruments like standard options and government debt securities.
Stocks present bigger obstacles. First, the seller has to locate the asset being sold & make sure they have clear title to it... which is tougher than it might seem, given the layers of abstraction/virtualization involved in the chain of ownership & custody, complicated in particular by "rehypothecation" involved in stock borrowing/lending for short sales... especially since stock borrow/lending record-keeping tends to be somewhat slipshod (cf. periodic uproar about "naked shorting" and "failure to deliver").
Second, the seller has to determine what exactly it is that they have sold... which, again, can be tougher than it might seem. You see, stocks are subject to all kinds of corporate actions (e.g. cash distributions, spin-offs, splits, liquidations, delistings...) A particular topic of keen interest is who exactly is entitled to large cash distributions - the buyer or the seller? Depending on the cutoff date (the "ex-dividend date"), the seller may need to deliver to the buyer just the shares of stock, or the shares plus a big chunk of cash - a significant difference in settlement. Determining the precise ex-dividend date (and so what exactly are the assets to be settled) can sometimes be very difficult... it's usually T-2, except in the case of large distributions, which are usually T+1, unless the regulatory authority has neglected to declare an ex-dividend date, in which case it defaults to standard DTC payment policy (i.e. T-2)... I've been involved in a few situations where the brokers involved were clueless, and full settlement of "due bills" for cash distributions to the buyer took several months of hard arguing.
So yeah, the brokers want a little time to get their records in order and settle the trade correctly.