in reply to Re^10: Computing results through Arrays
in thread Computing results through Arrays
robby_dobby already pointed out the actual mistake: you need to pass fnd_max() a reference to the hash, since that's what fnd_max() is expecting. See how I pass my hashes to set_column widths().
Now beyond that: First, I'd use a more descriptive subroutine name, like "max_value_of_hash", and drop the prototype. Prototypes are advanced juju and shouldn't be used most of the time. Second, if you want to get the largest value from a hash, you don't need to access the keys at all. Here are some examples, starting with the simplest and wordiest:
#!/usr/bin/env perl use 5.010; use strict; use warnings; # newbie but clean version sub max_value_of_hash { my $h = shift; my $max = 0; for my $v (values %$h){ if ($v > $max){ $max = $v; # keep setting $max to larger value } } return $max; } # more perlish and elegant version sub max_value_of_hash2 { my $h = shift; my $max = 0; $_ > $max ? $max = $_ : undef for values %$h; return $max; } # let a module do it sub max_value_of_hash3 { use List::Util qw(max); return max values %{$_[0]}; } my %hash = ( a => 1, b => 2, c => 5, d => 3 ); say max_value_of_hash( \%hash); say max_value_of_hash2(\%hash); say max_value_of_hash3(\%hash);
Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^12: Computing results through Arrays
by yasser8@gmail.com (Novice) on Jun 24, 2015 at 13:01 UTC | |
by aaron_baugher (Curate) on Jun 24, 2015 at 23:07 UTC | |
by yasser8@gmail.com (Novice) on Jun 26, 2015 at 09:32 UTC |
In Section
Seekers of Perl Wisdom