Attach keys and values ​​in perl

I have a hash with the following key / value pair

4 => model1 2 => model2 

I want the next line to be created from the specified 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; 

I get

 4 X model12Xmodel2 

How can I accomplish the desired result 4 X model1 , 2 X model2 ?

+6
source share
2 answers

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.

+16
source

You can also change your loop as follows:

 my @tokens =(); foreach my $key (keys %hash) { push @tokens, $string . join(' X ',$key, $hash{$key}); } print join(', ' , @tokens); 
+1
source

Source: https://habr.com/ru/post/903270/


All Articles