Perl: How to sort string elements?

How to sort string elements using Perl? You can use the sort() function of Perl to do the task. But this sort() function doesn't take a string as a parameter. It takes an array as parameter, and return the sorted array.

To use this function, first we need to convert the string into array, and using sort() function array will be at sorted order. Then using another function join() the array will be converted into string again. By the way, split() will make the string into array.

Here goes the example.

my $string = "7cc47ab2fac34278984cab446a8d0d2b";
print join('',sort(split(//,$string))) ."\n";

First splitting into array, then sort, and then back to array using join. For more Perl, you can read other topics from this blog http://icfun.blogspot.com/search/label/perl

Comments

eleete said…
"First splitting into array, then sort, and then back to array using join." think the author meant "and then back to a String using join.
Anonymous said…
or you can use Sort::Packed:

use Sort::Packed qw(sort_packed);
sort_packed C => $string;