Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push onto a hash key of array?

Tags:

raku

I am trying to push onto a hash of an array in Perl6.

The perl5 equivalent is:

my %c;
@{ $c{'USA'} } = qw(Seattle Madison Bozeman Portland);
push @{ $c{'USA'} }, 'Philadelphia';

but this in Perl6:

my %c;
%c<USA> = 'Seattle', 'Madison', 'Bozeman', 'Portland';
%c{'USA'}.append: 'Philadelphia';

gives this error

Cannot call 'append' on an immutable 'List'

I get a similar error for Perl6's push, which would seem to be okay given the example from https://docs.perl6.org/routine/push which shows %h<a>.push(1); Trying %c<USA>.push('Philadelphia') also fails

what am I doing wrong here? I don't see this error on search engine results

like image 251
con Avatar asked Feb 08 '19 20:02

con


People also ask

How do you push a hash into an array?

You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array.

How do I push a hash value?

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.

Can you hash an array?

Python Hashing (Hash tables and hashlib) While an array can be used to construct hash tables, array indexes its elements using integers. However, if we want to store data and use keys other than integer, such as 'string', we may want to use dictionary. Dictionaries in Python are implemented using hash tables.

How do you store an array in hash?

To assign that array to a hash element, you'd use either $b{"x"} = [@a] or $b{"x"} = \@a , depending on what you're trying to do. [@a] makes a new arrayref containing a copy of the current contents of @a . If the contents of @a change after that, it has no effect on $b{x} .


1 Answers

my %c;
%c<USA> = ['Seattle', 'Madison', 'Bozeman', 'Portland'];
%c{'USA'}.append: 'Philadelphia';

The brackets make an Array instead of a List

Links are to the Lists, sequences, and arrays docs which explain the difference, the primary being that List is immutable, while Array is not.

like image 92
Curt Tilmes Avatar answered Sep 20 '22 07:09

Curt Tilmes