### Re: Max value

by ameezys (Acolyte)
 on Apr 16, 2019 at 16:36 UTC ( #1232676=note: print w/replies, xml ) Need Help??

Thank you for the replies. Another question is, if b and c has the same value which is 3. how do I display both of it?

Replies are listed 'Best First'.
Re^2: Max value
by hippo (Chancellor) on Apr 16, 2019 at 17:19 UTC
Re^2: Max value
by tybalt89 (Prior) on Apr 16, 2019 at 17:32 UTC
```#!/usr/bin/perl

# https://perlmonks.org/?node_id=1232659

use strict;
use warnings;
use List::Util qw( reduce );

my %hashName = (a => 1, b => 3, c => 3);

sub allmax
{
reduce { \$a->[-1] > \$b->[-1] ? \$a :
\$a->[-1] < \$b->[-1] ? \$b :
[ @{\$a}[0..@\$a-2], @\$b ] } @_;
}

my \$maxref = allmax( map [ \$_, \$hashName{\$_} ], sort keys %hashName );

print "@\$maxref\n";

Outputs:

```b c 3

[-@\$a..-2] would have been slightly more obscure IMHO ;-)

Give a man a fish:  <%-{-{-{-<

Re^2: Max value
by Marshall (Canon) on Apr 16, 2019 at 21:37 UTC
```#!/usr/bin/perl
use strict;
use warnings;

my %hashName = (a => 1, b => 2, c => 3, d=>3);

#sort keys by descending order of their value
my @keys = sort {\$hashName{\$b} <=> \$hashName{\$a}} keys %hashName;

my \$max = \$hashName{\$keys[0]};

while (my \$key = shift @keys)
{
last if (\$hashName{\$key} < \$max);
print "\$key=>\$hashName{\$key}\n";
}
__END__
c=>3
d=>3
Update: I guess I should have added some comments to this post. There are very tricky and obtuse looking sort algorithms. Don't mistake "shorter code" or more "complex code" for "better code". When working with a hash of say <50 keys, my advice is to go with simple code. I start thinking about whipping out the "Perl nuclear weapons" when sort size gets above 1,000.
Re^2: Max value
by rsFalse (Hermit) on Apr 17, 2019 at 14:59 UTC
Another one variant:
```use strict;
use warnings;

my %hash_name = ( a => 1, b => 2, c => 3, d => 3 );

my %keys_of_max;
my \$key_of_max;
my \$numeric_cmp_result;

\$numeric_cmp_result = defined \$key_of_max
? ( eval join '<=>', map { \$hash_name{ \$_ } } \$_, \$key_of_max
+)
: 1
xor \$numeric_cmp_result > 0 and %keys_of_max = ( \$key_of_max = \$_
+=> 1 )
xor ( \$numeric_cmp_result or \$keys_of_max{ \$_ } = 1 )
for keys %hash_name;

print sort keys %keys_of_max;
OUTPUT:
```Useless use of logical xor in void context at perlmonks_Max_Value.pl l
+ine 26.
cd

Create A New User
Node Status?
node history
Node Type: note [id://1232676]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2020-10-30 02:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favourite web site is:

Results (277 votes). Check out past polls.

Notices?