Skip to content

Implement foreach-refalias syntax (for $var ...) #116

@fglock

Description

@fglock

Description

PerlOnJava does not currently support the foreach-refalias syntax introduced in Perl 5 (GH#24028), which allows iterating over a list while aliasing a reference variable.

Syntax

for \$variable ( list ) { ... }
for \@variable ( list ) { ... }
for \%variable ( list ) { ... }

Current Error

Expected token OPERATOR with text ( but got LexerToken{type=OPERATOR, text='\'} at op/decl-refs.t line 127, near "    for \\ "

Test Case

From perl5_t/t/op/decl-refs.t (commit 059a773b005a5728fa6dd213c406758c1f32e1b5):

# Scalar lexical
my $slexical = 42;
for \$slexical ( \1, \2, \3 ) { }
is $slexical, 42, 'scalar lexical restored after foreach-refalias';

# Array lexical
my @alexical = (42);
for \@alexical ( [1], [2], [3] ) { }
is $alexical[0], 42, 'array lexical restored after foreach-refalias';

# Hash lexical
my %hlexical = (k => 42);
for \%hlexical ( {k => 1}, {k => 2}, {k => 3} ) { }
is $hlexical{k}, 42, 'hash lexical restored after foreach-refalias';

# Package variables work similarly
our $spkgvar = 84;
for \$spkgvar ( \1, \2, \3 ) { }
is $spkgvar, 84, 'scalar pkgvar restored after foreach-refalias';

Expected Behavior

The foreach loop should:

  1. Accept a backslash-prefixed variable as the iteration variable
  2. Alias the reference variable to each element in the list during iteration
  3. Restore the original value of the variable after the loop completes

Implementation Notes

This requires changes to:

  • Lexer/Parser: Recognize the backslash prefix in foreach loop variable position
  • AST: Handle reference aliasing in foreach loops
  • Runtime: Implement proper aliasing semantics and value restoration

Related Test File

perl5_t/t/op/decl-refs.t lines 124-149

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions