In Perl, you can sort the character in the string by splitting the string into an array of characters, sort the array, and then join it back into a string.
In this example,
$str
.split('')
.sort
.join('')
.$str = 'hello world';
@chars = split('', $str);
@sorted_chars = sort @chars;
$sorted_str = join('', @sorted_chars);
print 'Sorted string in ascending order: ' . $sorted_str . "\n";
Sorted string in ascending order: dehllloorw
In this example,
$str
.split('')
.sort
with a custom comparison function.join('')
.$str = 'hello world';
@chars = split('', $str);
@sorted_chars = sort { $b cmp $a } @chars;
$sorted_str = join('', @sorted_chars);
print 'Sorted string in descending order: ' . $sorted_str . "\n";
Sorted string in descending order: wroolllehd
In this tutorial, we learned How to Sort Characters in String in Perl language with well detailed examples.