简体   繁体   中英

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?

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:

%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.

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

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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM