You can do:
my %hash = (4 => "model1", 2 => "model2"); my $str = join(", ", map { "$_ X $hash{$_}" } keys %hash); print $str;
Conclusion:
4 X model1, 2 X model2
How it works:
map { expr } list evaluates expr for each item in list and returns a list containing all the results of these evaluations. Here, "$_ X $hash{$_}" is evaluated for each hash key, so the result is a list of key X value strings. join will take care of putting commas between each of these lines.
Please note that your hash is a bit unusual if you store pairs (item, quantity). Usually it will be the other way around:
my %hash = ("model1" => 4, "model2" => 2); my $str = join(", ", map { "$hash{$_} X $_" } keys %hash);
because according to your scheme, you cannot store the same amount for two different elements in your hash.
source share