On Mon, Nov 29, 2004 at 10:15:52AM +1100, Michael Kraus wrote: > Which is better to use, a for/foreach loop or map function when doing > some basic comparisons and assignments? > > E.g. > > for my $datum (keys %{$rh_vars}) { > $max_length = length($datum) if length($datum) > $max_length; > } > > OR > > map { $max_length = ($max_length > length($_) ? $max_length : length($_) > } keys %$rh_vars; > > OR > > map { $max_length = length($_) if $length($_) > $max_length } keys > %$rh_vars; > > > Thanks heaps - some discussion on these basics would be great. My guess > is that it would be the last one as it doesn't assign $max_length a > value unless it has to.
Better is subjective here, especially as you don't say better for what, but I would agree that x = y if z would be preferable to x = z ? y : x. I would also suggest that using for instead of map in a void context is better style, even though you won't take the hit of creating a list to throw away that you used to, provided you are using a sufficiently recent perl. (By the way, perl-5-8-6 has just been released.) So, of your alternatives, I would use the first. But I would prefer to use: use List::Util "max"; my $max_length = max map length, keys %$rh_vars; -- Paul Johnson - [EMAIL PROTECTED] http://www.pjcj.net -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>