Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

How do I compare two strings against two arrays respectively?

( #39880=categorized question: print w/ replies, xml ) Need Help??
Contributed by dallok on Nov 03, 2000 at 23:17 UTC
Q&A  > strings


Description:

I have two strings $zero_arg and $sec_arg. I wish to compare each one against a file (routers.txt and interfaceses.txt) respectively. If $zero_arg is a good name then I want it to check the interface name. If $zero_arg is not a good name then DIE.

This is how I have the checking so far. Can I AND two if statements? Such as:

if (grep { $_ eq $zero_arg} @ARRAY) && {$_ ne $sec_arg} @anotherarray) + #Then do command.
Is there some way to make this work like that?

Answer: 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 }
Answer: HOw do I compare two strings against to arrays respectively
contributed by Adam

How about something like:

sub DoubleMatch { my( $item1, $item2, $array_ref1, $array_ref2 ) = @_; for( @$array_ref1 ) { if( $_ eq $item1 ) { for my $item ( @$array_ref2 ) { return 1 if $item eq $item2 } } return 0; } } # Then you can say: if( DoubleMatch( $item1, $item2, \@array1, \@array2 ) { # do stuff }
Not that I've tested that or anything.
Answer: HOw do I compare two strings against to arrays respectively
contributed by quidity

Yipee, another chance to use my favourite module... It might not run fast, but it'll be cool!

use Quantum::Superpositions; my $first = any(@routers); my $second = any(@interfaces); if ( ($first_arg eq $first) and ($second_arg ne $second)) { # .. do stuff .. # }
Answer: HOw do I compare two strings against to arrays respectively
contributed by Fastolfe

If we're going against two separate files here, it might not be most efficient to slurp each file up, and do our comparisons against the file's contents. Something like the following might be more efficient:

sub check_file { my $filename = shift; my $string = shift; open(F, "< $filename") or die "$filename: $!"; while(<F>) { close(F), return 1 if /\Q$string\E/; } close(F); return } if (search_file('file1', 'string1') && search_file('file2', 'string2')) { print "OK\n"; } else { print "No\n"; }
The question title itself is referring to arrays, in which case the other responses would be more appropriate, but the question itself has to do with file contents, so I thought I'd throw this out there.
Answer: HOw do I compare two strings against to arrays respectively
contributed by runrig

grep (or map) in a void context is generally considered bad. Better to store the array in a hash, especially if you access it more than once:

my %file; @routers{@ARRAY} = undef; @interfaces{@anotherarray} = undef if (exists $routers{$zero_arg} and not exists $interfaces{$sec_arg)) { #Do stuff }
Answer: How do I compare two strings against two arrays respectively?
contributed by ariels

Here's another way to do it, if I correctly understand what you want to do. You want to find an index $i for which $a[$i] eq $a and $b[$i] ne $b (that is, your condition holds at the same index). So why are you searching the array elements? It's better to search for an appropriate index!

@indices = grep { $a[$_] eq $a and $b[$_] ne $b } (0..$#a);

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • 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 chanting in the Monastery: (8)
    As of 2014-09-21 13:55 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      How do you remember the number of days in each month?











      Results (171 votes), past polls