[英]Perl Hash Keys + Values to variable
So I have a hash table like this: 所以我有一个像这样的哈希表:
M => 1
S => 50
I want to do something like this: 我想做这样的事情:
$var = map { "$hash{$_}"."$_\n" } keys %hash;
print $var;
so that I end up with a variable to print that looks like: 这样我最终得到一个要打印的变量,如下所示:
1M50S
Unfortunately the map statement doesn't work :( And yes it must be assigned to a variable because it is in an if statement and changes depending on conditions. Is there a nice clean way of doing this? 不幸的是,map语句不起作用:(是的,必须将其分配给变量,因为它在if语句中,并根据条件而变化。是否有一种很好的简洁方法?
Just use reverse: 只需使用反向:
my %hash = (M => 1, S => 50);
my $var = reverse %hash;
## use the next line instead if you need sorting
#my $var = join '', map { $_ . $hash{ $_ } } reverse sort keys %hash;
## or this
#my $var = reverse map { $_ => $hash{ $_ } } reverse sort keys %hash;
print $var; ## outputs 1M50S
You can, for example, concatenate first the value + key and then do a join: 例如,您可以先连接value +键,然后再进行联接:
%hash = (M => 1, S => 50);
$var = join("", map {$hash{$_} . $_} keys %hash);
print $var . "\n" ;
Added: If you want to sort by values, asumming they are numeric: 补充:如果要按值排序,则假设它们是数字:
%hash = (M => 1, S => 50, Z => 6);
$var = join("", map {$hash{$_} . $_} sort { $hash{$a} <=> $hash{$b} } keys %hash);
print $var . "\n" ;
1M6Z50S
you have to know that keys %hash
is unordered, which means its order may or may not be what you want. 您必须知道keys %hash
是无序的,这意味着其顺序可能不是您想要的。
I recommend using a ordered list here to specify keys. 我建议在此处使用有序列表来指定键。
and there is an unclean way 而且有一种不干净的方法
%time=(M=>1,S=>50);
$var=join"",map{"$time{$_}$_"}('M','S');
#=> $var='1M50S'
If MIDNSHP=X
is all of the keys in the order you want them, then write 如果MIDNSHP=X
是您想要的所有键,请输入
my $var = join '', map "$hash{$_}$_", split //, 'MIDNSHP=X';
If the hash may contain less than a complete set of keys, then use this instead 如果散列可能包含少于完整的键集,请改用此键
my $var = join '', map "$hash{$_}$_", grep $hash{$_}, split //, 'MIDNSHP=X';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.