Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is postderef syntax on hashes supported?

Let's say I have

my %foo;

Can I set keys foo, bar, baz to a b c by taking a slice and doing parallel assignment with postfix notation?

%foo->@{qw/foo bar baz/} = qw/a b c/

I used this syntax and I was told it was only "accidentally working". I don't see it generating a warning, and I also don't see it documented anywhere. Is this behavior supported or not?

like image 299
NO WAR WITH RUSSIA Avatar asked Apr 15 '20 20:04

NO WAR WITH RUSSIA


People also ask

How do I reference a hash in Perl?

Similar to the array, Perl hash can also be referenced by placing the '\' character in front of the hash. The general form of referencing a hash is shown below. %author = ( 'name' => "Harsha", 'designation' => "Manager" ); $hash_ref = \%author; This can be de-referenced to access the values as shown below.

How do I declare an array of hash in Perl?

@values = @{ $hash{"a key"} }; To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value.

What is Perl reference?

Perl Reference is a way to access the same data but with a different variable. A reference in Perl is a scalar data type which holds the location of another variable. Another variable can be scalar, hashes, arrays, function name etc.


1 Answers

The left side of -> is supposed to be an expression that returns a reference. Use anything else at your own risk.


%foo->{a} used to work.

$ 5.10t/bin/perl -e'my %foo; %foo->{a} = 1; print "ok\n";'
ok

This was deemed to be bug.

$ 5.12t/bin/perl -e'my %foo; %foo->{a} = 1; print "ok\n";'
Using a hash as a reference is deprecated at -e line 1.
ok

$ 5.20t/bin/perl -e'my %foo; %foo->{a} = 1; print "ok\n";'
Using a hash as a reference is deprecated at -e line 1.
ok

$ 5.22t/bin/perl -e'my %foo; %foo->{a} = 1; print "ok\n";'
Can't use a hash as a reference at -e line 1.

There's no reason to believe %foo->@{...} is any more valid than %foo->{...}.


Bug reported.

like image 89
ikegami Avatar answered Sep 16 '22 18:09

ikegami