Paul Johnson wrote:
>
> > Is there a function to find out if a given value exists in an array?
> >
> > What I think of is something like &has_element([EMAIL PROTECTED], $value), which
> > should return either a boolean value or the index containing the value
> > (undef if $value is not found).
> > I'm sure something like this exists. Or do I need to write this myself?
>
> Something close exists. I think I'd probably code it as:
>
> use List::Util "first";
>
> sub has_element
> {
> my ($array, $value) = @_;
> first { $_ eq $value } @$array
> }
Except that this will return the /value/ of the element
for which the block returns true, which isn't obvious from the
call. It's identical to
sub has_element {
my ($array, $value) = @_;
foreach (@$array) {
return $_ if $_ eq $value;
}
return;
}
which, to my mind, is preferable as it is clearer what's going on. It's
certainly no slower.
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>