I have a hash with the following key/value pair
4 => model1
2 => model2
I want the following string created from the above hash
4 X model1 , 2 X model2
I tried the following
my %hash,
foreach my $keys (keys %hash) {
my $string = $string . join(' X ',$keys,$hash{$keys});
}
print $string;
What I get is
4 X model12Xmodel2
How can I accomplish the desired result 4 X model1 , 2 X model2?
You could do:
Output:
How it works:
map { expr } listevaluatesexprfor every item inlist, and returns the list that contains all the results of these evaluations. Here,"$_ X $hash{$_}"is evaluated for each key of the hash, so the result is a list ofkey X valuestrings. Thejointakes care of putting the commas in between each of these strings.Note that your hash is a bit unusual if you’re storing (item,quantity) pairs. It would usually be the other way around:
because with your scheme, you can’t store the same quantity for two different items in your hash.