Perl: The spaceship operator

At school we learned a new operator for Perl called the “spaceship operator“.  It’s just this: <=>
Let your imagination speak 🙂

The operator compares 2 internal variables $a and $b.
You can’t name them $x and $y, it’s predefined in Perl that you should use the operator with variables $a and $b.

In the example below I sort 2 arrays:

#!/usr/bin/perl
use strict;
use warnings;

my (@array1, @array1_sorted, @array2, @array2_sorted);

@array1 = @array2 = (10, 5, -2, -11, -35, 7, 1, 0, 6);

# ----------------------------------------------------
# Method 1
# @sortedArray = (sort { condition(s) } @arrayToSort);
# ----------------------------------------------------
@array1_sorted = (sort
		  {
		    if ($a < $b)
		    {
		      return -1;
		    }
		    elsif ($a > $b)
		    {
		      return 1;
		    }
		    else
		    {
		      return 0;
		    }
		  }
		  @array1);

print join "\n",@array1_sorted;

print "\n\n";

# ----------------------------------------------------
# Method 2
# Using the <=> operator.
# ----------------------------------------------------
@array2_sorted = (sort {$a <=> $b} @array2);

print join "\n",@array2_sorted;

The Output:

-35
-11
-2
0
1
5
6
7
10

-35
-11
-2
0
1
5
6
7
10

When you want to sort an array of strings just use cmp instead of <=>.

 

Update: line 40 was wrong but the output is the same. Tnx Fuss 😉

#!/usr/bin/perl
use strict;
use warnings;my (@array1, @array1_sorted, @array2, @array2_sorted);

@array1 = @array2 = (10, 5, -2, -11, -35, 7, 1, 0, 6);

# —————————————————-
# Method 1
# @sortedArray = (sort { condition(s) } @arrayToSort);
# —————————————————-
@array1_sorted = (sort
{
if ($a < $b)
{
return -1;
}
elsif ($a > $b)
{
return 1;
}
else
{
return 0;
}
}
@array1);

print join “\n”,@array1_sorted;

print “\n\n”;

# —————————————————-
# Method 2
# Using the <=> operator.
# —————————————————-
@array2_sorted = (sort {$a <=> $b} @array2);

print join “\n”,@array1_sorted;

Advertisements

2 thoughts on “Perl: The spaceship operator

  1. Da’s valsspelen é:

    30.print join “\n”,@array1_sorted;
    40.print join “\n”,@array1_sorted;

    2x dezelfde array afprinten? Volgens mij doet die spacecake operator juist niets! ;P

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