0

How to count the each element of same index number?

my @a = qw"A B C D E F";
my @b = qw"A B C C";
my $count = 0;
for($i = 0; $i<=scalar @a; $i++){
    for($j = 0; $j <= scalar @b; $j++){
        if($a[$i] eq $b[$j]){
            $count++;
        }
    }
}
print "Total: $count";

I expect the output is:
Total:3

The output is done by count only the same element of the index key? How can i do it?

1 Answer 1

3

There are two potential interpretations to your problem:

1. How does one count the intersection of two arrays?

A hash is an ideal data structure to test for existance:

use strict;
use warnings;

my @a = qw"A B C D E F";
my @b = qw"A B C C";

my %b = map {$_ => 1} @b;

my $count = scalar grep {$b{$_}} @a;

print "Total: $count";

Outputs:

Total: 3

Additional perldoc reference: How do I compute the difference of two arrays? How do I compute the intersection of two arrays?

2. How does one test element equality between two arrays, index to index?

If this is your question, then you do not need two loops, just a single iterator.

use strict;
use warnings;

use List::Util qw(min);

my @a = qw"A B C D E F";
my @b = qw"A B C C";

my $count = scalar grep {$a[$_] eq $b[$_]} (0..min($#a, $#b));

print "Total: $count";

Outputs:

Total: 3
Sign up to request clarification or add additional context in comments.

3 Comments

That depends on which problem you actually want. If it's (1), then you can follow the link to find the difference between two arrays. If it's (2), then you can just subtract @a - $count and @b - $count to get 3 and 1 respectively.
Useless use of scalar! If assigning to a scalar isn't obviously scalar context, what is.
@ikegami You are correct of course. But I don't mind a little bit of redundancy when trying to educate. What is obvious to us, may not be obvious to a beginner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.