Jan Eden wrote:
>
> a while ago, I wrote a little subroutine to test wether a given element is in a
> given array:
>
> sub contains {
>
> my $result = 0;
> my $contained = shift;
> foreach (@_) {
> if ($_ eq $contained){ $result = 1; }
> }
> $result;
> }
>
> Now I found a nicer solution in "Learning Perl Objects, References & Modules"
> and adapted it:
>
> sub contains {
> my $contained = shift;
> my $result = grep { $contained eq $_ } @_;
> }
>
> Smart. But immediately after giving this example, Randal notes that this is not
> the best solution for testing large arrays. Can anyone give me a hint to what he
> might have meant? Or, to put it this way: Randal, what did you think of writing
> this?
Hi Jan.
If you want to test a static (unchanging) array for the containment of many different
values you should build a hash out of the array elements:
my @data = 'a' .. 'm';
my %data_hash;
@[EMAIL PROTECTED] = ();
Then simply check for the existence of a hash element with the required value as
a key:
for (split '', 'robdixon') {
if (exists $data_hash{$_}) {
printf "Element %s found in [EMAIL PROTECTED]", $_;
}
else {
printf "Element %s isn't in [EMAIL PROTECTED]", $_;
}
}
**OUTPUT
Element r isn't in @data
Element o isn't in @data
Element b found in @data
Element d found in @data
Element i found in @data
Element x isn't in @data
Element o isn't in @data
Element n isn't in @data
But this isn't practical if the hash keeps needing to be rebuilt because the array
hash changed. Depending on your data it may be a good idea to start with a hash anyway,
but for a general overview of the topic look at:
perldoc -q "array contains"
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>