Commit b5b75bc2c4 for perl
commit b5b75bc2c422d24fa52d53918e310ece59183f16
Author: Paul Evans <leonerd@leonerd.org.uk>
Date: Thu Nov 12 14:42:07 2026 +0000
Fix index values for multivariable foreach with indexed+reverse
Previously, the effect of the `reversed` flag was not taken into account
when assigning index values in the optimised loop. This resulted in the
elements being numbered backwards.
Fixes [GH#25052]
diff --git a/lib/builtin.t b/lib/builtin.t
index 0d245d57c3..fcdce4ad31 100644
--- a/lib/builtin.t
+++ b/lib/builtin.t
@@ -412,6 +412,15 @@ package FetchStoreCounter {
ok(eq_array(\@output, [qw( [0]=six [1]=seven [2]=eight [3]=nine )] ),
'foreach + builtin::indexed LIST' );
+
+ undef @output;
+
+ foreach my ( $idx, $val ) ( builtin::indexed reverse qw( zero one two ) ) {
+ push @output, "[$idx]=$val";
+ }
+
+ ok(eq_array(\@output, [qw( [0]=two [1]=one [2]=zero )]),
+ 'foreach + builtin::indexed reverse LIST' );
}
# indexed + foreach + refalias (GH#24999)
diff --git a/pp_hot.c b/pp_hot.c
index 5e27b6f62d..f44db02f3e 100644
--- a/pp_hot.c
+++ b/pp_hot.c
@@ -5152,8 +5152,11 @@ PP(pp_iter)
if (UNLIKELY(pflags & OPpITER_INDEXED) && (i == 0)) {
SvREFCNT_dec(*itersvp);
/* here ix is really a stack pointer offset; we have to
- * calculate the real index */
- *itersvp = newSViv(ix - cx->blk_loop.state_u.stack.basesp - 1);
+ * calculate the real index. What value that is depends on
+ * the OPpITER_REVERSED flag */
+ *itersvp = (pflags & OPpITER_REVERSED)
+ ? newSViv(cx->blk_oldsp - ix)
+ : newSViv(ix - cx->blk_loop.state_u.stack.basesp - 1);
++i;
++itersvp;