Skip to content

Incompatible change in 5.42: builtin::indexed and two-variable foreach loop #23595

@jkeenan

Description

@jkeenan

(The following bug report was originally posted by Michael Schapp on the perl5-porters mailing list as "Incompatible change in 5.42".)

In perldelta for 5.42, under Performance Enhancements:

Code that uses the indexed function from the builtin module to generate a list of index/value pairs out of an array or list which is then passed into a two-variable foreach list to unpack those again is now optimised to be more efficient.

        my @array = (...);

        foreach my ($idx, $val) (builtin::indexed @array) {
            ...
        }

        foreach my ($idx, $val) (builtin::indexed LIST...) {
            ...
        }

In particular, a temporary list twice the size of the original is no longer generated. Instead, the loop iterates down the original array or list in-place directly, in the same way that foreach (@array) or foreach (LIST) would do.

Although this is a nice enhancement, isn't that an incompatible change?

    $ /opt/perl-5.40/bin/perl -E 'my @a = (1..5); for my ($i,$x) (indexed @a) { $x += $i }; say for @a;'
    1
    2
    3
    4
    5
    $ /opt/perl-5.42/bin/perl -E 'my @a = (1..5); for my ($i,$x) (indexed @a) { $x += $i }; say for @a;'
    1
    3
    5
    7
    9

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions