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
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.
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.
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.
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} .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With