Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Answer: How do I compare two strings against two arrays respectively?

( #40004=categorized answer: print w/ replies, xml ) Need Help??

Q&A > strings > How do I compare two strings against two arrays respectively? contributed by Russ

Yes. You just need to call grep twice (you had incorrect syntax, by leaving off the second grep)
if (grep {$_ eq $zero_arg} @ARRAY) and not grep {$_ eq $sec_arg} @anot +herarray){ doSomething(); }
You want to use not (or '!') on the second grep statement (rather than in it (ne) because you want to know if the second array does not contain $sec_arg. What you had would have told you if every line in @anotherarray contained $sec_arg.

Clear as mud? :-)

grep is not in void context in this case, because we are testing the scalar value of the array returned by grep. Each grep returns us an array of the lines containing the test string. In scalar context, that becomes the number of elements in that list. If there are no elements in the list, we didn't find the string in @Array, and the statement is false.

This is not the most CPU-efficient way to accomplish your task, but it is the most PROGRAMMER-efficient way. Weigh the benefits accordingly. If you will be testing for very many strings (in my opinion >1 is enough), you should use one of the other methods (like building a hash, as suggested by runrig).

Happy grepping!

P.S. Based on your question, it sounds like, for each string, you want to find it in the first array. If so, then check the second array for that string. If the string does not appear in the first array, die. Right?

for my $Str ($zero_arg, $sec_arg){ die "$Str is not in routers.txt" unless grep {$_ eq $Str} @Routers; if (grep {$_ eq $Str} @Interfaces){ # The string is a good name, and it appears in @Interfaces # so do something } }
If you want to know that both strings are good names before you then check both strings against interfaces:
for my $Str ($zero_arg, $sec_arg){ die "$Str is not in routers.txt" unless grep {$_ eq $Str} @Routers; } if (grep {$_ eq $zero_arg} @Interfaces and grep {$_ eq $sec_arg} @Inte +rfaces){ # They are both there # So do something }

Comment on Answer: How do I compare two strings against two arrays respectively?
Select or Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2014-08-30 14:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (293 votes), past polls