Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join keys and values in perl

Tags:

perl

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?

like image 670
user238021 Avatar asked Dec 07 '11 08:12

user238021


2 Answers

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.

like image 148
Mat Avatar answered Sep 28 '22 09:09

Mat


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);
like image 40
Ashwinee K Jha Avatar answered Sep 28 '22 08:09

Ashwinee K Jha