I try postderef and key-value slice in Perl 5.19.5

I try postderef in Perl 5.19.5. The following code don't work.

my $params = {
  foo => 1,
  bar => 2,
  baz => 3
};

my $new_params = {};
$new_params->%{'FOO', 'BAR'} = $params->%{'foo', 'bar'};

I expect {FOO => 1, BAR => 2}.
But left side assignment don't work. Is this specification or bug?

3 Comments

That's not the way ->%{} is supposed to work.

$a->%{foo} returns foo => $a->{foo}, and you can't assign to such a thing.

You probably meant $new_params->@{'FOO', 'BAR'} = $params->@{'foo', 'bar'};, which does the assignment you're looking for.

Why did you think you needed to switch sigils?

If you wrote this in traditional circumfix style, you wouldn’t write

%{$new_params}{'FOO', 'BAR'} = %{$params}{'foo', 'bar'};

because that doesn’t work either. You would write

@{$new_params}{'FOO', 'BAR'} = @{$params}{'foo', 'bar'};

And for postfix dereference you use exactly the same sigils as before.

Leave a comment

About Yuki Kimoto

user-pic I'm Perl Programmer. I LOVE Perl. I want to contribute Perl community and Perl users.