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:
my %hash = (4 => "model1", 2 => "model2");
my $str = join(", ", map { "$_ X $hash{$_}" } keys %hash);
print $str;
Output:
4 X model1, 2 X model2
How it works:
map { expr } list
evaluates expr
for every item in list
, 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 of key X value
strings. The join
takes 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:
my %hash = ("model1" => 4, "model2" => 2);
my $str = join(", ", map { "$hash{$_} X $_" } keys %hash);
because with your scheme, you can't store the same quantity for two different items in your hash.
You can also modify your loop as follows:
my @tokens =();
foreach my $key (keys %hash) {
push @tokens, $string . join(' X ',$key, $hash{$key});
}
print join(', ' , @tokens);
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