0

In array List

my @array = ('val1','val2','val3','val4','val1');

I would like to get output like below

Output:
No of repetition of Val1 = 2 times

Please help me to get this output.

Thanks in advance!

1
  • 2
    In Perl, {…} creates a hash reference, not an array – those are initialized using a list (…). You should consider to use strict; use warnings; as a safety net. Commented Dec 3, 2013 at 12:25

2 Answers 2

2

Use a hash:

my @array = ('val1','val2','val3','val4','val1');    
my %seen;
my $element;
foreach $element (@array){
    $seen{$element}++
}

foreach my $val (keys %seen){
    print "No of repetition of $val = $seen{$val} times\n" if ($seen{$val} > 1);
}

Prints:

No of repetition of val1 = 2 times
Sign up to request clarification or add additional context in comments.

Comments

2
my @array = ('val1','val2','val3','val4','val1');

my %seen;
$seen{$_}++ for @array;

print "No of repetition of $_ = $seen{$_} times\n"
  for grep $seen{$_} >1, sort keys %seen;

Comments

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.