See the core module List::Util, especially all.
use strict; use warnings; use List::Util 'all'; # see below for how to properly create your hash my %words = ( foo => 1, bar => 1, baz => 1, qux => 1, ); my @must_exist = ( 'bar', 'qux', ); my $all_found = all { exists $words{ $_ } } @must_exist; if ( $all_found ) { ... }
As for the code you have:
... yes, but using pairs. So an array of ('foo', 'bar', 'baz', 'qux') will give a hash with only two key-value pairs, with keys foo and baz. Thus later searching on the keys will not give the desired results.my %hash = @allwords; #puts array in hash to search / compare.
If you do want to create a hash with a key for each element in a list, use map:
@array = ('foo', 'bar', 'baz', 'qux'); %hash = map { $_ => 1 } @array;
... this won't work. You need to check whether each key exists individually:if (exists $hash{'word1' && 'word2' && 'word3'}) { ...do stuff ; }
if ( exists $hash{'foo'} and exists $hash{'bar'} ) { ... }
... this has several problems, which I will let other monks explain, but all of which can be avoided by using all.if ( grep { $_ eq 'word1' && 'word2' } @allwords ) { ...do stuff; }
Hope this helps!
update: added comments on OP code, then example with all
In reply to Re: Check array for several matches
by 1nickt
in thread Check array for several matches
by Bman70
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |