I am new to perl. I need to understand how can I map one array (as keys) to another (as values) to result in a hash using foreach loop:
@one = ("A", "B", "C");
@two = ("a", "b", "c");
I wrote the following code but it does not work when I slice the hash??
%hash;
foreach $i (one) {
print $i, "=>" , $ii = shift @two, "\n"
}
You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.
To add another hash to an array, we first initialize the array with our data. Then, we use push to push the new hash to the array. The new hash should have all of its data. As shown below, you can see the difference between the two arrays before and after pushing a new hash.
@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.
map() function in Perl evaluates the operator provided as a parameter for each element of List. For each iteration, $_ holds the value of the current element, which can also be assigned to allow the value of the element to be updated.
Assuming the answer to my question in the comment is "yes", here's a couple of approaches.
Given:
my @one = qw/A B C/;
my @two = qw/1 2 3/;
Using hash slices:
my %hash;
@hash{@one} = @two;
Using the List::MoreUtils module from CPAN:
use List::MoreUtils qw/zip/;
my %hash = zip @one, @two;
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