Somalia's parliament elected a moderate Islamist leader as the country's new president early Saturday, handing over the elusive task of stabilizing a country wracked by violence and anarchy for nearly 20 years.

Sheik Sharif Sheik Ahmed was elected in neighbouring Djibouti after the last president — a former soldier, rebel and warlord named Abdullahi Yusuf — resigned in December after failing to pacify the country during his four-years as president.

Ahmed was chairman of the Islamic Courts Union that ran Mogadishu for six months in 2006 before Ethiopian soldiers drove them from power. His election raises hopes that he will bring many of Somalia's Islamic factions into a more inclusive government.

But the Western-backed government wields little control in Somalia— just a few blocks of the capital, Mogadishu, where African Union peacekeepers patrol. An Islamic insurgent group called al-Shabab, who say they don't recognize the government, has taken over most of Somalia.

The U.S. considers al-Shabab a terror organization with links to al-Qaeda.

Somalia's parliament has been meeting all week in neighbouring Djibouti to choose the new president. Sharif won easily with 293 votes after the other front-runner, the prime minister, withdrew.

The second-place candidate received 126 votes.

Sharif was due to be sworn in later Saturday, then fly to the Ethiopian capital for an African Union summit.

The arid and impoverished Horn of Africa nation of some 8 million people has not had a functioning government since clan-based militias overthrew the a dictator in 1991 and then turned on each other.

Pirates prey on international shipping freely from Somalia's lawless shores, and analysts fear an extremist Islamic administration could become a haven for international terrorists.

There have been more than a dozen previous peace efforts and three previous governments were formed, but they never managed to take effective control of the country.