in reply to Check array for several matches
A shorter, more portable solution that uses only Perl built-ins.
Also, since you are starting out with Perl, knowledge of these techniques will be essential in your journey to Perl greatness!
Upto my %hash should be clear from the previous responses.
Enhancement (thank you, AnomalousMonk):
The deduplication code which I previously thought would be necessary is not actually required.
The next statement prints do stuff if the specified condition is met. Let us look at each part of the condition.
Evaluated in scalar context, arrays in Perl return the number of elements they contain. So @required returns the number of elements it contains.
@hash{@required} uses the hash-slice syntax to extract a list of values associated with the keys that happen to be members of @required. Trying to extract a value against a key which does not exist in a hash results in an undefined value.
Enhancement:
The defined test is not really required, as it is implicit.
grep { $_ } returns a list of all defined elements from the list previously returned. Recall that non-existent keys return an undefined value, which evaluates to false in the boolean context, so they are weeded out by this.
Enhancement (thank you, haukex):
In scalar context, grep returns the number of elements in the list that match the condition. Since that is what we need, we just use the value in scalar context directly.
I leave figuring out the remainder of the code as an exercise to the reader.
#!/usr/bin/env perl use strict; use warnings; my @allwords = qw( this is a list of words that is required for tests +); my @required = qw( this is a list of words that is required ); my %hash = map { $_ => 1 } @allwords; print "do stuff\n" if @required == grep { $_ } @hash{@required}; my @notthere = qw( this list is not there in allwords ); print "don't do stuff\n" unless @notthere == grep { $_ } @hash{@notthere};
I know this could get a bit overwhelming, so feel free to ask for any clarifications.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Check array for several matches
by haukex (Archbishop) on May 11, 2017 at 13:54 UTC | |
|
Re^2: Check array for several matches
by AnomalousMonk (Archbishop) on May 11, 2017 at 15:30 UTC |