in reply to Common Perl Idioms
Regarding in_list I personally would prefer either:
sub in_list {my $target=shift; return 0+grep { $_ eq $target } @_}
if you really care about the count (and want to use grep) or if you want fast then:
sub in_list {my $target=shift; $_ eq $target and return 1 for @_; retu +rn}
using the for modifier avoids creating and managing an extra scope (like grep,map and for statements) and avoiding the slice I think is more efficient. Afaik perl will have to create the sliced list first before iterating so you are really just copying the whole array which could get expensive for a large list.
Anyway heres an interesting/useful one :
sub find_first_index { my $target=shift; push @_,$target; my $i=0; $i++ while $_[$i] ne $target; return $i==$#_ ? undef : $i }
Which is a nice trick to reduce the cost of the tight loop. Dunno if more modern perls have been optimised enough that these tricks are unnecessary though. Its been a while since I benchmarked this stuff last.
First they ignore you, then they laugh at you, then they fight you, then you win.
-- Gandhi
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Common Perl Idioms
by ysth (Canon) on Jul 23, 2004 at 19:59 UTC | |
by demerphq (Chancellor) on Jul 23, 2004 at 20:09 UTC | |
by ysth (Canon) on Jul 23, 2004 at 20:12 UTC | |
Re^2: Common Perl Idioms
by ihb (Deacon) on Jul 24, 2004 at 00:45 UTC | |
by demerphq (Chancellor) on Jul 24, 2004 at 02:47 UTC | |
by BrowserUk (Patriarch) on Jul 24, 2004 at 03:35 UTC |