Help - Search - Member List - Calendar
Full Version: "sort" usage in arrays
WorkTheWeb Forums > Webmaster Resources > Perl Beginner Help
Support our Sponsors!
Vineet Pande
Hello!
In the following code:

**************************************************
#!/usr/bin/perl
use warnings;
use strict;
my @unsorted = (1, 2, 11, 24, 3, 36, 40, 4);
my @number = sort { $a <=> $b } @unsorted;
print "Numeric sort: @numbern";
**************************************************
returns 1 2 3 4 11 24 36 40

what I don't understand is how the block functions here: we did not define
$a and $b? Also I donot understand this kind of block usage.

Any comments appreciated!
cheers
v

_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today it's FREE!
http://messenger.msn.click-url.com/go/onm0...1ave/direct/01/

Ing. Branislav Gerzo
Vineet Pande [VP], on Monday, July 04, 2005 at 20:34 (+0000) wrote:

VP> what I don't understand is how the block functions here: we did not define
VP> $a and $b? Also I donot understand this kind of block usage.

when you don't know something, try ask perl:

perldoc -q sort

if you find (or know) functions name, try

perldoc -f sort

everything is explained there.

--

...m8s, cu l8r, Brano.

[A nudist is one who suffers from clothostrophobia.]

Gerard Robin
On Mon, Jul 04, 2005 at 08:34:26PM +0000 Vineet Pande wrote:
QUOTE
Hello!
In the following code:

**************************************************
#!/usr/bin/perl
use warnings;
use strict;
my @unsorted = (1, 2, 11, 24, 3, 36, 40, 4);
my @number = sort { $a <=> $b } @unsorted;
print "Numeric sort: @numbern";
**************************************************
returns 1 2 3 4 11 24 36 40

what I don't understand is how the block functions here: we did not define
$a and $b? Also I donot understand this kind of block usage.

Any comments appreciated!

in
Perl literacy course

lecture #5

Sorting and Perl

Shlomo Yona <[Email Removed]> http://cs.haifa.ac.il/~shlomo/

----------------------------------------------------------------------------
$a and $b

$a and $b are two elements of the list being compared during some iteration.

To optimize the calling of the sortsub, Perl bypasses the usual passing of
arguments via @_, using instead a more efficient special-purpose method.

Within the sortsub, the special package global variables $a and $b are
aliases for the two operands being compared.

The sortsub must return a number less than 0, equal to 0, or greater than 0,
depending on the result of comparing the sortkeys of $a and $b.
-----------------------------------------------------------------------------

hth
--
Grard


PHP Help | Linux Help | Web Hosting | Reseller Hosting | SSL Hosting
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2005 Invision Power Services, Inc.