CINXE.COM

sort - Perldoc Browser

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>sort - Perldoc Browser</title> <link rel="search" href="/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser"> <link rel="canonical" href="https://perldoc.perl.org/functions/sort"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" /> <style> body { background: #f4f4f5; color: #020202; } .navbar-dark { background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%); background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%); background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0); background-repeat: repeat-x; } .navbar-dark .navbar-nav .nav-link, .navbar-dark .navbar-nav .nav-link:focus { color: #fff } .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 } #wrapperlicious { margin: 0 auto; font: 0.9em 'Helvetica Neue', Helvetica, sans-serif; font-weight: normal; line-height: 1.5em; margin: 0; padding: 0; } #wrapperlicious h1 { font-size: 1.5em } #wrapperlicious h2 { font-size: 1.3em } #wrapperlicious h3 { font-size: 1.1em } #wrapperlicious h4 { font-size: 0.9em } #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3, #wrapperlicious h4, #wrapperlicious dt { color: #020202; margin-top: 1em; margin-bottom: 1em; position: relative; font-weight: bold; } #wrapperlicious a { color: inherit; text-decoration: underline } #wrapperlicious #toc { text-decoration: none } #wrapperlicious a:hover { color: #2a2a2a } #wrapperlicious a img { border: 0 } #wrapperlicious :not(pre) > code { color: inherit; background-color: rgba(0, 0, 0, 0.04); border-radius: 3px; font: 0.9em Consolas, Menlo, Monaco, monospace; padding: 0.3em; } #wrapperlicious dd { margin: 0; margin-left: 2em; } #wrapperlicious dt { color: #2a2a2a; font-weight: bold; margin-left: 0.9em; } #wrapperlicious p { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious li > p { margin-bottom: 0; margin-top: 0; } #wrapperlicious pre { border: 1px solid #c1c1c1; border-radius: 3px; font: 100% Consolas, Menlo, Monaco, monospace; margin-bottom: 1em; margin-top: 1em; } #wrapperlicious pre > code { display: block; background-color: #f6f6f6; font: 0.9em Consolas, Menlo, Monaco, monospace; line-height: 1.5em; text-align: left; white-space: pre; padding: 1em; } #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious ul { list-style-type: square; } #wrapperlicious ul ul { margin-bottom: 0px; margin-top: 0px; } #footer { font-size: 0.8em; padding-top: 0.5em; text-align: center; } #more { display: inline; font-size: 0.8em; } #perldocdiv { background-color: #fff; border: 1px solid #c1c1c1; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; margin-left: auto; margin-right: auto; padding: 3em; padding-top: 1em; max-width: 960px; } #moduleversion { float: right } #wrapperlicious .leading-notice { font-style: italic; padding-left: 1em; margin-top: 1em; margin-bottom: 1em; } #wrapperlicious .permalink { display: none; left: -0.75em; position: absolute; padding-right: 0.25em; text-decoration: none; } #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink, #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink, #wrapperlicious dt:hover .permalink { display: block; } </style> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-KVNWBNT5FB'); gtag('config', 'UA-50555-3'); </script> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="/"><img src="/images/perl_camel_30.png" width="30" height="30" class="d-inline-block align-top" alt="Perl Camel Logo"> Perldoc Browser</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">blead</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-stable"> <a class="dropdown-item" href="/functions/sort">Latest</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.1/functions/sort">5.40.1</a> <a class="dropdown-item" href="/5.40.0/functions/sort">5.40.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.3/functions/sort">5.38.3</a> <a class="dropdown-item" href="/5.38.2/functions/sort">5.38.2</a> <a class="dropdown-item" href="/5.38.1/functions/sort">5.38.1</a> <a class="dropdown-item" href="/5.38.0/functions/sort">5.38.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.36.3/functions/sort">5.36.3</a> <a class="dropdown-item" href="/5.36.2/functions/sort">5.36.2</a> <a class="dropdown-item" href="/5.36.1/functions/sort">5.36.1</a> <a class="dropdown-item" href="/5.36.0/functions/sort">5.36.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.34.3/functions/sort">5.34.3</a> <a class="dropdown-item" href="/5.34.2/functions/sort">5.34.2</a> <a class="dropdown-item" href="/5.34.1/functions/sort">5.34.1</a> <a class="dropdown-item" href="/5.34.0/functions/sort">5.34.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.32.1/functions/sort">5.32.1</a> <a class="dropdown-item" href="/5.32.0/functions/sort">5.32.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.30.3/functions/sort">5.30.3</a> <a class="dropdown-item" href="/5.30.2/functions/sort">5.30.2</a> <a class="dropdown-item" href="/5.30.1/functions/sort">5.30.1</a> <a class="dropdown-item" href="/5.30.0/functions/sort">5.30.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.28.3/functions/sort">5.28.3</a> <a class="dropdown-item" href="/5.28.2/functions/sort">5.28.2</a> <a class="dropdown-item" href="/5.28.1/functions/sort">5.28.1</a> <a class="dropdown-item" href="/5.28.0/functions/sort">5.28.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.26.3/functions/sort">5.26.3</a> <a class="dropdown-item" href="/5.26.2/functions/sort">5.26.2</a> <a class="dropdown-item" href="/5.26.1/functions/sort">5.26.1</a> <a class="dropdown-item" href="/5.26.0/functions/sort">5.26.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.24.4/functions/sort">5.24.4</a> <a class="dropdown-item" href="/5.24.3/functions/sort">5.24.3</a> <a class="dropdown-item" href="/5.24.2/functions/sort">5.24.2</a> <a class="dropdown-item" href="/5.24.1/functions/sort">5.24.1</a> <a class="dropdown-item" href="/5.24.0/functions/sort">5.24.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.22.4/functions/sort">5.22.4</a> <a class="dropdown-item" href="/5.22.3/functions/sort">5.22.3</a> <a class="dropdown-item" href="/5.22.2/functions/sort">5.22.2</a> <a class="dropdown-item" href="/5.22.1/functions/sort">5.22.1</a> <a class="dropdown-item" href="/5.22.0/functions/sort">5.22.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.20.3/functions/sort">5.20.3</a> <a class="dropdown-item" href="/5.20.2/functions/sort">5.20.2</a> <a class="dropdown-item" href="/5.20.1/functions/sort">5.20.1</a> <a class="dropdown-item" href="/5.20.0/functions/sort">5.20.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.18.4/functions/sort">5.18.4</a> <a class="dropdown-item" href="/5.18.3/functions/sort">5.18.3</a> <a class="dropdown-item" href="/5.18.2/functions/sort">5.18.2</a> <a class="dropdown-item" href="/5.18.1/functions/sort">5.18.1</a> <a class="dropdown-item" href="/5.18.0/functions/sort">5.18.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.3/functions/sort">5.16.3</a> <a class="dropdown-item" href="/5.16.2/functions/sort">5.16.2</a> <a class="dropdown-item" href="/5.16.1/functions/sort">5.16.1</a> <a class="dropdown-item" href="/5.16.0/functions/sort">5.16.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.14.4/functions/sort">5.14.4</a> <a class="dropdown-item" href="/5.14.3/functions/sort">5.14.3</a> <a class="dropdown-item" href="/5.14.2/functions/sort">5.14.2</a> <a class="dropdown-item" href="/5.14.1/functions/sort">5.14.1</a> <a class="dropdown-item" href="/5.14.0/functions/sort">5.14.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.5/functions/sort">5.12.5</a> <a class="dropdown-item" href="/5.12.4/functions/sort">5.12.4</a> <a class="dropdown-item" href="/5.12.3/functions/sort">5.12.3</a> <a class="dropdown-item" href="/5.12.2/functions/sort">5.12.2</a> <a class="dropdown-item" href="/5.12.1/functions/sort">5.12.1</a> <a class="dropdown-item" href="/5.12.0/functions/sort">5.12.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.10.1/functions/sort">5.10.1</a> <a class="dropdown-item" href="/5.10.0/functions/sort">5.10.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.9/functions/sort">5.8.9</a> <a class="dropdown-item" href="/5.8.8/functions/sort">5.8.8</a> <a class="dropdown-item" href="/5.8.7/functions/sort">5.8.7</a> <a class="dropdown-item" href="/5.8.6/functions/sort">5.8.6</a> <a class="dropdown-item" href="/5.8.5/functions/sort">5.8.5</a> <a class="dropdown-item" href="/5.8.4/functions/sort">5.8.4</a> <a class="dropdown-item" href="/5.8.3/functions/sort">5.8.3</a> <a class="dropdown-item" href="/5.8.2/functions/sort">5.8.2</a> <a class="dropdown-item" href="/5.8.1/functions/sort">5.8.1</a> <a class="dropdown-item" href="/5.8.0/functions/sort">5.8.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.2/functions/sort">5.6.2</a> <a class="dropdown-item" href="/5.6.1/functions/sort">5.6.1</a> <a class="dropdown-item" href="/5.6.0/functions/sort">5.6.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.005_04/functions/sort">5.005_04</a> <a class="dropdown-item" href="/5.005_03/functions/sort">5.005_03</a> <a class="dropdown-item" href="/5.005_02/functions/sort">5.005_02</a> <a class="dropdown-item" href="/5.005_01/functions/sort">5.005_01</a> <a class="dropdown-item" href="/5.005/functions/sort">5.005</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-dev"> <a class="dropdown-item active" href="/blead/functions/sort">blead</a> <a class="dropdown-item" href="/5.41.10/functions/sort">5.41.10</a> <a class="dropdown-item" href="/5.41.9/functions/sort">5.41.9</a> <a class="dropdown-item" href="/5.41.8/functions/sort">5.41.8</a> <a class="dropdown-item" href="/5.41.7/functions/sort">5.41.7</a> <a class="dropdown-item" href="/5.41.6/functions/sort">5.41.6</a> <a class="dropdown-item" href="/5.41.5/functions/sort">5.41.5</a> <a class="dropdown-item" href="/5.41.4/functions/sort">5.41.4</a> <a class="dropdown-item" href="/5.41.3/functions/sort">5.41.3</a> <a class="dropdown-item" href="/5.41.2/functions/sort">5.41.2</a> <a class="dropdown-item" href="/5.41.1/functions/sort">5.41.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.1-RC1/functions/sort">5.40.1-RC1</a> <a class="dropdown-item" href="/5.40.0-RC2/functions/sort">5.40.0-RC2</a> <a class="dropdown-item" href="/5.40.0-RC1/functions/sort">5.40.0-RC1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.39.10/functions/sort">5.39.10</a> <a class="dropdown-item" href="/5.39.9/functions/sort">5.39.9</a> <a class="dropdown-item" href="/5.39.8/functions/sort">5.39.8</a> <a class="dropdown-item" href="/5.39.7/functions/sort">5.39.7</a> <a class="dropdown-item" href="/5.39.6/functions/sort">5.39.6</a> <a class="dropdown-item" href="/5.39.5/functions/sort">5.39.5</a> <a class="dropdown-item" href="/5.39.4/functions/sort">5.39.4</a> <a class="dropdown-item" href="/5.39.3/functions/sort">5.39.3</a> <a class="dropdown-item" href="/5.39.2/functions/sort">5.39.2</a> <a class="dropdown-item" href="/5.39.1/functions/sort">5.39.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.3-RC1/functions/sort">5.38.3-RC1</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-nav"> <a class="dropdown-item" href="/blead/perl">Perl</a> <a class="dropdown-item" href="/blead/perlintro">Intro</a> <a class="dropdown-item" href="/blead/perl#Tutorials">Tutorials</a> <a class="dropdown-item" href="/blead/perlfaq">FAQs</a> <a class="dropdown-item" href="/blead/perl#Reference-Manual">Reference</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/blead/perlop">Operators</a> <a class="dropdown-item" href="/blead/functions">Functions</a> <a class="dropdown-item" href="/blead/variables">Variables</a> <a class="dropdown-item" href="/blead/modules">Modules</a> <a class="dropdown-item" href="/blead/perlutil">Utilities</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/blead/perldelta">Release Notes</a> <a class="dropdown-item" href="/blead/perlcommunity">Community</a> <a class="dropdown-item" href="/blead/perlhist">History</a> </div> </li> </ul> <ul class="navbar-nav"> <script> function set_expand (expand) { var perldocdiv = document.getElementById('perldocdiv'); var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width'); var expanded = (width == '' || width == 'none') ? true : false; if (expand === null) { expand = !expanded; } if ((expand && !expanded) || (!expand && expanded)) { perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px'); var button_classlist = document.getElementById('content-expand-button').classList; if (expand) { button_classlist.add('btn-light'); button_classlist.remove('btn-outline-light'); } else { button_classlist.add('btn-outline-light'); button_classlist.remove('btn-light'); } } return expand; } function toggle_expand () { var expand = set_expand(null); document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC'; } function read_expand () { return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { if (read_expand()) { set_expand(true); } }); } else if (read_expand()) { set_expand(true); } </script> <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-4" onclick="toggle_expand()">Expand</button> </ul> <form class="form-inline" method="get" action="/blead/search"> <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search" value=""> </form> </div> </nav> <div id="wrapperlicious" class="container-fluid"> <div id="perldocdiv"> <div id="links"> <a href="/blead/functions">functions</a> / <a href="/blead/functions/sort">sort</a> <div id="more"> (<a href="/blead/functions/sort.txt">source</a>, <a href="https://metacpan.org/pod/perlfunc#sort-SUBNAME-LIST">CPAN</a>) </div> </div> <div class="leading-notice"> You are viewing the version of this documentation from Perl blead. This is a development version of Perl. </div> <div class="leading-notice"> <strong>sort</strong> may also refer to the module: <a href="/blead/sort">sort</a> </div> <dl> <dt id="sort-SUBNAME-LIST"><a class="permalink" href="#sort-SUBNAME-LIST">#</a><a id="sort"></a>sort SUBNAME LIST </dt> <dd> </dd> <dt id="sort-BLOCK-LIST"><a class="permalink" href="#sort-BLOCK-LIST">#</a><a id="sort1"></a>sort BLOCK LIST</dt> <dd> </dd> <dt id="sort-LIST"><a class="permalink" href="#sort-LIST">#</a><a id="sort2"></a>sort LIST</dt> <dd> <p>In list context, this sorts the LIST and returns the sorted list value. In scalar context, the behaviour of <a href="/blead/functions/sort"><code>sort</code></a> is undefined.</p> <p>If SUBNAME or BLOCK is omitted, <a href="/blead/functions/sort"><code>sort</code></a>s in standard string comparison order. If SUBNAME is specified, it gives the name of a subroutine that returns a numeric value less than, equal to, or greater than <code>0</code>, depending on how the elements of the list are to be ordered. (The <code>&lt;=&gt;</code> and <code>cmp</code> operators are extremely useful in such routines.) SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use. In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine.</p> <p>If the subroutine&#39;s prototype is <code>($$)</code>, the elements to be compared are passed by reference in <a href="/blead/perlvar#%40_"><code>@_</code></a>, as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables <code>$a</code> and <code>$b</code> (see example below).</p> <p>If the subroutine is an XSUB, the elements to be compared are pushed on to the stack, the way arguments are usually passed to XSUBs. <code>$a</code> and <code>$b</code> are not set.</p> <p>If two or more elements of LIST compare the same (i.e. the comparison operation returns 0 for them), they retain the relative order they had in LIST. In other words, sorting is stable (and has been since v5.8.0).</p> <p>The values to be compared are always passed by reference and should not be modified.</p> <p>You also cannot exit out of the sort block or subroutine using any of the loop control operators described in <a href="/blead/perlsyn">perlsyn</a> or with <a href="/blead/functions/goto"><code>goto</code></a>.</p> <p>When <a href="/blead/locale"><code>use locale</code></a> (but not <code>use locale &#39;:not_characters&#39;</code>) is in effect, <code>sort LIST</code> sorts LIST according to the current collation locale. See <a href="/blead/perllocale">perllocale</a>.</p> <p><a href="/blead/functions/sort"><code>sort</code></a> returns aliases into the original list, much as a for loop&#39;s index variable aliases the list elements. That is, modifying an element of a list returned by <a href="/blead/functions/sort"><code>sort</code></a> (for example, in a <code>foreach</code>, <a href="/blead/functions/map"><code>map</code></a> or <a href="/blead/functions/grep"><code>grep</code></a>) actually modifies the element in the original list. This is usually something to be avoided when writing clear code.</p> <p>Examples:</p> <pre><code># sort lexically my @articles = sort @files; # same thing, but with explicit sort routine my @articles = sort {$a cmp $b} @files; # now case-insensitively my @articles = sort {fc($a) cmp fc($b)} @files; # same thing in reversed order my @articles = sort {$b cmp $a} @files; # sort numerically ascending my @articles = sort {$a &lt;=&gt; $b} @files; # sort numerically descending my @articles = sort {$b &lt;=&gt; $a} @files; # this sorts the %age hash by value instead of key # using an in-line function my @eldest = sort { $age{$b} &lt;=&gt; $age{$a} } keys %age; # sort using explicit subroutine name sub byage { $age{$a} &lt;=&gt; $age{$b}; # presuming numeric } my @sortedclass = sort byage @class; sub backwards { $b cmp $a } my @harry = qw(dog cat x Cain Abel); my @george = qw(gone chased yz Punished Axed); print sort @harry; # prints AbelCaincatdogx print sort backwards @harry; # prints xdogcatCainAbel print sort @george, &#39;to&#39;, @harry; # prints AbelAxedCainPunishedcatchaseddoggonetoxyz # inefficiently sort by descending numeric compare using # the first integer after the first = sign, or the # whole record case-insensitively otherwise my @new = sort { ($b =~ /=(\d+)/)[0] &lt;=&gt; ($a =~ /=(\d+)/)[0] || fc($a) cmp fc($b) } @old; # same thing, but much more efficiently; # we&#39;ll build auxiliary indices instead # for speed my (@nums, @caps); for (@old) { push @nums, ( /=(\d+)/ ? $1 : undef ); push @caps, fc($_); } my @new = @old[ sort { $nums[$b] &lt;=&gt; $nums[$a] || $caps[$a] cmp $caps[$b] } 0..$#old ]; # same thing, but without any temps my @new = map { $_-&gt;[0] } sort { $b-&gt;[1] &lt;=&gt; $a-&gt;[1] || $a-&gt;[2] cmp $b-&gt;[2] } map { [$_, /=(\d+)/, fc($_)] } @old; # using a prototype allows you to use any comparison subroutine # as a sort subroutine (including other package&#39;s subroutines) package Other; sub backwards ($$) { $_[1] cmp $_[0]; } # $a and $b are # not set here package main; my @new = sort Other::backwards @old; ## using a prototype with function signature use feature &#39;signatures&#39;; sub function_with_signature :prototype($$) ($one, $two) { return $one &lt;=&gt; $two } my @new = sort function_with_signature @old;</code></pre> <p>Warning: syntactical care is required when sorting the list returned from a function. If you want to sort the list returned by the function call <code>find_records(@key)</code>, you can use:</p> <pre><code>my @contact = sort { $a cmp $b } find_records @key; my @contact = sort +find_records(@key); my @contact = sort &amp;find_records(@key); my @contact = sort(find_records(@key));</code></pre> <p>If instead you want to sort the array <code>@key</code> with the comparison routine <code>find_records()</code> then you can use:</p> <pre><code>my @contact = sort { find_records() } @key; my @contact = sort find_records(@key); my @contact = sort(find_records @key); my @contact = sort(find_records (@key));</code></pre> <p><code>$a</code> and <code>$b</code> are set as package globals in the package the sort() is called from. That means <code>$main::a</code> and <code>$main::b</code> (or <code>$::a</code> and <code>$::b</code>) in the <code>main</code> package, <code>$FooPack::a</code> and <code>$FooPack::b</code> in the <code>FooPack</code> package, etc. If the sort block is in scope of a <code>my</code> or <code>state</code> declaration of <code>$a</code> and/or <code>$b</code>, you <i>must</i> spell out the full name of the variables in the sort block :</p> <pre><code>package main; my $a = &quot;C&quot;; # DANGER, Will Robinson, DANGER !!! print sort { $a cmp $b } qw(A C E G B D F H); # WRONG sub badlexi { $a cmp $b } print sort badlexi qw(A C E G B D F H); # WRONG # the above prints BACFEDGH or some other incorrect ordering print sort { $::a cmp $::b } qw(A C E G B D F H); # OK print sort { our $a cmp our $b } qw(A C E G B D F H); # also OK print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H); # also OK sub lexi { our $a cmp our $b } print sort lexi qw(A C E G B D F H); # also OK # the above print ABCDEFGH</code></pre> <p>With proper care you may mix package and my (or state) <code>$a</code> and/or <code>$b</code>:</p> <pre><code>my $a = { tiny =&gt; -2, small =&gt; -1, normal =&gt; 0, big =&gt; 1, huge =&gt; 2 }; say sort { $a-&gt;{our $a} &lt;=&gt; $a-&gt;{our $b} } qw{ huge normal tiny small big}; # prints tinysmallnormalbighuge</code></pre> <p><code>$a</code> and <code>$b</code> are implicitly local to the sort() execution and regain their former values upon completing the sort.</p> <p>Sort subroutines written using <code>$a</code> and <code>$b</code> are bound to their calling package. It is possible, but of limited interest, to define them in a different package, since the subroutine must still refer to the calling package&#39;s <code>$a</code> and <code>$b</code> :</p> <pre><code>package Foo; sub lexi { $Bar::a cmp $Bar::b } package Bar; ... sort Foo::lexi ...</code></pre> <p>Use the prototyped versions (see above) for a more generic alternative.</p> <p>The comparison function is required to behave. If it returns inconsistent results (sometimes saying <code>$x[1]</code> is less than <code>$x[2]</code> and sometimes saying the opposite, for example) the results are not well-defined.</p> <p>Because <code>&lt;=&gt;</code> returns <a href="/blead/functions/undef"><code>undef</code></a> when either operand is <code>NaN</code> (not-a-number), be careful when sorting with a comparison function like <code>$a &lt;=&gt; $b</code> any lists that might contain a <code>NaN</code>. The following example takes advantage that <code>NaN != NaN</code> to eliminate any <code>NaN</code>s from the input list.</p> <pre><code>my @result = sort { $a &lt;=&gt; $b } grep { $_ == $_ } @input;</code></pre> <p>In the current version of Perl, the <code>sort</code> function is implemented via the mergesort algorithm.</p> </dd> </dl> </div> <div id="footer"> <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p> <p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <script src="/js/highlight.pack.js"></script> <script>hljs.highlightAll();</script> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10