How has support for return values (wantarray) changed across recent Perl versions?

In recent Perl versions, the handling of return values using the `wantarray` function has undergone some important changes. The `wantarray` function allows developers to determine the context in which a subroutine was called, enabling them to return different types of values depending on that context (scalar, list, etc.).

Historically, Perl allowed a subroutine to tailor its return values based on whether it was called in scalar or list context, but the nuances of this behavior have evolved. Subsequent Perl releases have refined performance optimizations and introduced clearer semantics for these contexts, ensuring more predictable outcomes for developers.

        sub example_sub {
            if (wantarray) {
                return (1, 2, 3); # Return list in list context
            } else {
                return 42; # Return scalar in scalar context
            }
        }

        my @list = example_sub(); # Called in list context
        my $scalar = example_sub(); # Called in scalar context

        print "@list"; # Outputs: 1 2 3
        print $scalar; # Outputs: 42
    

Perl wantarray return values subroutine context scalar context list context Perl versions