[Wellington-pm] comparison and assignment: insignificant optimisation
Richard Hector
richard at walnut.gen.nz
Mon Jun 16 02:59:29 PDT 2014
Hi all,
I often find it necessary to do some comparison, then do something with
one of the operands. Here's a common example:
sub max_length {
my @list = @_;
my $current_max;
foreach my $item (@list) {
if (length($item) > $current_max) {
$current_max = length($item);
}
}
return $current_max;
}
What irritates me is that the length of the string is evaluated twice.
That, I admit, is probably not very expensive, but it irritates me
nonetheless, and it could be worse if it's something more complicated
than finding the length of a string.
I know I could get round that by putting the result of length into a
temporary variable, but that irritates me just by adding lines of code :-)
I was wondering if there was a simpler way - maybe something like one of
those action-assignment operators, like += or ||=.
Any suggestions?
Richard
More information about the Wellington-pm
mailing list