Perl Programming/Keywords/cmp

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: closedir Keywords Next: connect

The cmp keyword[edit | edit source]

cmp is a binary function that returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument. In other words, cmp does the same textually what the binary function <=> does.

Syntax[edit | edit source]

  EXPRESSION cmp EXPRESSION

Examples[edit | edit source]

The code
use strict;
use warnings;

my @array = ("Hotel", "Alpha", "Foxtrott", "Bravo", "India", "Charlie", "10", "-10", "9", "-9", "Echo", "Delta");

my @sorted_array = (sort { $a cmp $b } @array);

print join(",", @sorted_array), "\n";
returns array contents sorted alphabetically:
-10, 10, Alpha, Bravo, Charlie, Delta, Echo, Foxtrott, Hotel, India

See also[edit | edit source]

Previous: closedir Keywords Next: connect