b2938d
From 390fe0c0d09aadc66f644e9eee4aa1245221188c Mon Sep 17 00:00:00 2001
b2938d
From: David Mitchell <davem@iabyn.com>
b2938d
Date: Tue, 25 Aug 2020 13:15:25 +0100
b2938d
Subject: [PATCH] sort { return foo() } ...
b2938d
MIME-Version: 1.0
b2938d
Content-Type: text/plain; charset=UTF-8
b2938d
Content-Transfer-Encoding: 8bit
b2938d
b2938d
GH #18081
b2938d
b2938d
A sub call via return in a sort block was called in void rather than
b2938d
scalar context, causing the comparison result to be discarded.
b2938d
b2938d
This because when a sort block is called it is not a real function
b2938d
call, even though a sort block can be returned from. Instead, a
b2938d
CXt_NULL is pushed on the context stack. Because this isn't a sub-ish
b2938d
context type (unlike CXt_SUB, CXt_EVAL etc) there is no 'caller sub'
b2938d
on the context stack to be found to retrieve the caller's context
b2938d
(i.e. cx->cx_gimme).
b2938d
b2938d
This commit fixes it by special-casing Perl_gimme_V().
b2938d
b2938d
Ideally at some future point, a new context type, CXt_SORT, should be
b2938d
added. This would be used instead of CXt_NULL when a sort BLOCK is
b2938d
called. Like other sub-ish context types, it would have an old_cxsubix
b2938d
field and PL_curstackinfo->si_cxsubix would point to it. This would
b2938d
eliminate needing special-case handling in places like Perl_gimme_V().
b2938d
b2938d
Signed-off-by: Petr Písař <ppisar@redhat.com>
b2938d
---
b2938d
 inline.h    |  2 +-
b2938d
 t/op/sort.t | 12 +++++++++++-
b2938d
 2 files changed, 12 insertions(+), 2 deletions(-)
b2938d
b2938d
diff --git a/inline.h b/inline.h
b2938d
index a8240efb9c..6fbd5abfea 100644
b2938d
--- a/inline.h
b2938d
+++ b/inline.h
b2938d
@@ -2086,7 +2086,7 @@ Perl_gimme_V(pTHX)
b2938d
         return gimme;
b2938d
     cxix = PL_curstackinfo->si_cxsubix;
b2938d
     if (cxix < 0)
b2938d
-        return G_VOID;
b2938d
+        return PL_curstackinfo->si_type == PERLSI_SORT ? G_SCALAR: G_VOID;
b2938d
     assert(cxstack[cxix].blk_gimme & G_WANT);
b2938d
     return (cxstack[cxix].blk_gimme & G_WANT);
b2938d
 }
b2938d
diff --git a/t/op/sort.t b/t/op/sort.t
b2938d
index f2e139dff0..8e387fb90d 100644
b2938d
--- a/t/op/sort.t
b2938d
+++ b/t/op/sort.t
b2938d
@@ -7,7 +7,7 @@ BEGIN {
b2938d
     set_up_inc('../lib');
b2938d
 }
b2938d
 use warnings;
b2938d
-plan(tests => 203);
b2938d
+plan(tests => 204);
b2938d
 use Tie::Array; # we need to test sorting tied arrays
b2938d
 
b2938d
 # these shouldn't hang
b2938d
@@ -1202,3 +1202,13 @@ SKIP:
b2938d
     $fillb = undef;
b2938d
     is $act, "01[sortb]2[fillb]";
b2938d
 }
b2938d
+
b2938d
+# GH #18081
b2938d
+# sub call via return in sort block was called in void rather than scalar
b2938d
+# context
b2938d
+
b2938d
+{
b2938d
+    sub sort18081 { $a + 1 <=> $b + 1 }
b2938d
+    my @a = sort { return &sort18081 } 6,1,2;
b2938d
+    is "@a", "1 2 6", "GH #18081";
b2938d
+}
b2938d
-- 
b2938d
2.25.4
b2938d