Pass the first argument/parameter as a hash reference. If any additional argument is passed the function will return the length of the longest key instead of the length of the longest value.
# last mod: Wed Aug 20 2003 23:08 UTC # by [Intrepid], with quality tweaking by [broquaint] ;-) sub max_strl { UNIVERSAL::isa( (my $h = shift) , 'HASH') or die "Must pass a hashref!\n"; my $ml = 0; length > $ml and $ml = length for ( @_ ? keys %$h : values %$h ); return $ml; }
For (a dumb) example, to pretty-printout a hash of varying-length items like this, with stuff on both front and behind:
#!/usr/bin/env perl use strict; use warnings; $\ = "\n"; my $i = 'A'; my(%hash) = map(($i++, $_), split(/:/, $ENV{'PATH'}, 0)); my $maxl = max_strl(\%hash) + 5; my $format1 = "PathEle %3s%${maxl}s% 10u Kb used"; foreach (sort keys %hash) { my $use_of_disk = "du -ks $hash{$_}"; printf "$format1\n", $_, $hash{$_}, (split /\s+/,`$use_of_disk`)[0 +]; } exit 0;
Using max_strl with printf() is just the start. Your imagination is the only limit! {grin}.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: max_strl - Get length of longest string in a hash
by diotalevi (Canon) on Aug 20, 2003 at 22:12 UTC | |
Re: max_strl - Get length of longest string in a hash
by DrHyde (Prior) on Aug 21, 2003 at 09:43 UTC | |
by liz (Monsignor) on Aug 21, 2003 at 10:20 UTC | |
by DrHyde (Prior) on Aug 21, 2003 at 13:55 UTC | |
by liz (Monsignor) on Aug 21, 2003 at 14:12 UTC | |
by DrHyde (Prior) on Aug 21, 2003 at 15:30 UTC | |
| |
Re: max_strl - Get length of longest string in a hash
by Aristotle (Chancellor) on Aug 24, 2003 at 06:12 UTC |