Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

How do I compare two strings against two arrays respectively?

by dallok (Initiate)
on Nov 03, 2000 at 23:17 UTC ( #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!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            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?
    [stevieb]: man, I absolutely LOVE driving in the worst winter conditions. In the mountainous roads, there are extremely few (if any) other drivers. I love the challenge. I've been doing extreme off-road my whole life, and as I said, I'm always well...
    [stevieb]: ...prepared for even the very worst
    Discipulus seems a part of the globe very unfrindly with Kawasaki riders..
    [thezip]: My doggies love it when it snows
    [perldigious]: As long as you are a good "boy scout" stevieb, more power to you... but I like my Jeep, and don't like the idea of rolling it or crashing it in to anything. :-)
    [thezip]: Me, not as much.
    [perldigious]: Mine too thezip, especially my German Shepherd. He looks like he is about to die of heat exhaustion all summer, so he goes nuts when winter comes and he can play in the snow.
    [stevieb]: my main off-road vehicle nowadays is a strengthened mercedes ML320. I'm very hard on it, but I've never had any real issues at all (I love how small and light it is, and it has a very, very good centre of gravity for how I roll)

    How do I use this? | Other CB clients
    Other Users?
    Others surveying the Monastery: (11)
    As of 2016-12-06 16:48 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      On a regular basis, I'm most likely to spy upon:













      Results (112 votes). Check out past polls.