PPCs icon indicating copy to clipboard operation
PPCs copied to clipboard

Arrayref and hashref destructuring in subroutine signatures and assignment

Open akarelas opened this issue 1 year ago • 1 comments

It would be nice if we could do:

sub foo ([$x, $y]) {
    say "$x, $y";
}

...instead of:

sub foo ($pair) {
    my ($x, $y) = @$pair;
    say "$x, $y";
}

...but also (if the previous has been done):

my { $x, $y } = { x => 5, y => 6 };

...or:

my { x => $value_x, y => $value_y } = { x => 5, y => 6 };

Would certainly help with users of RxPerl, who often write code like:

$observable->pipe(
    op_pairwise,
    op_map(sub ($pair) {
        my ($old, $new) = @$pair;
        ...
    }),
);

akarelas avatar Oct 04 '24 08:10 akarelas

I like that the my { x => $value_x, y => $value_y } = { x => 5, y => 6 } de-structuring looks like regular structuring.

It almost feels like I should be able to put any reference constructor on the my side and have any variable referenced there get lvalue'ed up:

my { advanced => { destructuring => [undef, undef, $third_value] } } = $deep_struct;

How far can this go?

Can it express de-structure into a lexical sub or the symbol table? Maybe even capturing a method call on an object as a code-reference my \&callback = \&$obj->method

guest20 avatar Oct 04 '24 13:10 guest20