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
In reply to Re: Common Perl Idioms
by demerphq
in thread Common Perl Idioms
by eric256
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |