What needs to consider when sorting arrays in Perl

I ‘ve working with a coding challenge, my solution leads me to sort an array of numbers.

As the Perl variables are scalar, and sorting syntax in Perl is as easy as eating a cookie.


@sorted = sort @unsorted;

But it’s not promissed the array elements are numbers, so by default, it will be sorted by alphabet order.

This will lead to: 11 < 2

So the result is not what we desire.

If we cannot debug the right case, it will be so frustrated.


When sorting array of numbers, you have to pass a custom comparison function to Perl’s sort routine, as below:

@sorted = sort { $a <=> $b } @unsorted;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s