I forgot to cc: the list...

2009/12/10 Noah <noah-l...@enabled.com>:
> I am hoping to figure out the best Way to write something.  I have two
> arrays @previous_hostnames and @hostnames.
>
> I want to figure out if there is at least one matching element in
> @previous_hostnames that is found in @hostnames.

You can use a lookup table to eliminate one loop:

  my %previous_hostnames = map { $_ => 1 } @previous_hostnames;
  for my $hostname (@hostnames) {
      if ($previous_hostname{$hostname}) {
          $found = 1;
          last;
      }
   }

The first line builds a hash with keys being previous hostnames with
values 1 for every one of them. Now you only have to check if
$previous_hostname{$hostname} is true. Usually when you are comparing
a string to a list of strings you should use a lookup table for best
performance.

Or you can use Quantum::Superpositions:

use Quantum::Superpositions;
my $found = 1 if any(@hostnames) eq any(@previous_hostnames);

By the way, you have to use eq instead of == if you want to compare
strings or otherwise you are comparing your hostnames as numbers which
is probably not what you want. For example:

"a" == "b" is true because both are 0 when converted to numbers
"a" eq "b" is false because eq compares strings

See: http://perldoc.perl.org/perlop.html#Equality-Operators

Rafał Pocztarski

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to