[Omaha.pm] if ($a > $b) { $b = $a }

Andy Lester andy at petdance.com
Thu Jan 20 09:23:11 PST 2005


On Thu, Jan 20, 2005 at 10:56:45AM -0600, Jay Hannah (jhannah at omnihotels.com) wrote:
> 
> I seem to write this pattern in my code a lot when I'm trying to find the maximum value of something:
> 
> if ($a > $b) {
>    $b = $a;
> }

First, you can write it as $b=$a if $a>$b, which takes up less visual
space.

> Is there some slick Perl operator that does that cleaner?

You can write yourself a max() function:

$b = max($b,$a);

There's one in List::Util that, I believe, comes by default these days.


> if ($running_simul{$type} > $stats{$type}{'max simul'}{$time}) {
>     $stats{$type}{'max simul'}{$time} = $running_simul{$type};
> }

You could do something like an update_if_larger() function:

update_if_larger( $stats{$type}{'max simul'}{$time}, $running_simul{$type} );

sub update_if_larger { $_[0] = $_[1] if $_[1] > $_[0] );

xoa

-- 
Andy Lester => andy at petdance.com => www.petdance.com => AIM:petdance


More information about the Omaha-pm mailing list