From: Bob Showalter <[EMAIL PROTECTED]> > Tim Musson wrote: > > Hey all, > > > > I need to return the largest of 3 vars. Is there a better way than > > nested IF statements? Maybe put them in an array and sort it? > > You can write the sort without needing a separate array: > > $max = (sort {$b<=>$a} ($x, $y, $z))[0]; > > Or, you can do something like this > > $max = ($max = ($x > $y) ? $x : $y) > $z ? $max : $z; > > (I'm sure somebody can simplify that) > > If you get more than 3 vars, the sort is probably the cleanest way to > write it.
Just for kicks I benchmarked a few solutions: #!perl use Benchmark; use strict; my $x = 4; my $y = 2; my $z = 45; sub Bob2 { my $max; $max = ($max = ($x > $y) ? $x : $y) > $z ? $max : $z; return $max; } sub Bob { my $max = (sort {$b<=>$a} ($x, $y, $z))[0]; return $max; } sub GetLast { my $max = (sort ($x, $y, $z))[-1]; return $max; } sub ListContext { my ($max) = sort {$b<=>$a} ($x, $y, $z); return $max; } sub For3If { my $max = $x;$max = ($_ > $max ? $_ : $max) for ($x, $y, $z); return $max; } sub ForModIf { my $max = $x; for ($x, $y, $z) {$max = $_ if $_ > $max}; return $max; } timethese 1000000, { Bob => \&Bob, Bob2 => \&Bob2, GetLast => \&GetLast, ListContext => \&ListContext, For3If => \&For3If, ForModIf => \&ForModIf, }; __END__ Benchmark: timing 1000000 iterations of Bob, Bob2, Bob2J, For3If, ForModIf, GetL ast, ListContext... Bob: 3 wallclock secs ( 2.55 usr + 0.00 sys = 2.55 CPU) @ 391696.04/s (n=1000000) Bob2: 2 wallclock secs ( 1.51 usr + 0.00 sys = 1.51 CPU) @ 660938.53/s (n=1000000) For3If: 6 wallclock secs ( 5.36 usr + 0.00 sys = 5.36 CPU) @ 186636.80/s (n=1000000) ForModIf: 4 wallclock secs ( 5.09 usr + 0.00 sys = 5.09 CPU) @ 196579.52/s (n=1000000) GetLast: 2 wallclock secs ( 2.75 usr + 0.00 sys = 2.75 CPU) @ 363108.21/s (n=1000000) ListContext: 3 wallclock secs ( 2.31 usr + 0.00 sys = 2.31 CPU) @ 432338.95/s (n=1000000) (Look at the CPU time, not the wallclock!) Jenda ===== [EMAIL PROTECTED] === http://Jenda.Krynicky.cz ===== When it comes to wine, women and song, wizards are allowed to get drunk and croon as much as they like. -- Terry Pratchett in Sourcery -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]