Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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

by Russ (Deacon)
on Nov 04, 2000 at 20:42 UTC ( [id://40004]=note: print w/replies, xml ) Need Help??


in reply to How do I compare two strings against two arrays respectively?

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 }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://40004]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-26 07:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found