ansh batra has asked for the wisdom of the Perl Monks concerning the following question:

hi monks
Happy new year to everyone
i have any array with me say @arr which contains number of words(may contain spaces)
and i also have a text (in array) which contains a text of say 1000 lines.
i need to do
foreach $a(@arr) { if $a is occurring more than two times in text then print "$a"; }
i am using if(grep {$_ eq $a} @text) but here i cannot specify the count.
please help

Replies are listed 'Best First'.
Re: REGEX:getting the count of occerence
by GrandFather (Saint) on Jan 02, 2012 at 05:51 UTC

    Why not show us what you are actually using rather than making us guess?

    In general if you need to check if 'somethings' exist in a (large) 'something' else in Perl you tend to us a hash which is populated from the 'something' and keyed by potential 'somethings'. For example you could:

    #!/usr/bin/perl use warnings; use strict; my %words; while (defined (my $line = <DATA>)) { ++$words{lc $_} for $line =~ /(\w+)/g; } printf "There are %d occurences of '%s'\n", $words{lc $_}, $_ for grep {exists $words{$_} && $words{$_} > 1} qw(text i); __DATA__ hi monks Happy new year to everyone i have any array with me say @arr which contains number of words(may c +ontain spaces) and i also have a text (in array) which contains a text of say + 1000 lines. i need to do

    which prints:

    There are 2 occurences of 'text' There are 3 occurences of 'i'
    True laziness is hard work
Re: REGEX:getting the count of occerence
by Marshall (Canon) on Jan 02, 2012 at 08:01 UTC
    foreach my $a(@arr) { $a =~ s/^\s*//; #trim leading spaces $a =~ s/\s*$//; #trim trailing spaces my $count = grep {$_ =~ /($a)/g} @text; print "\'$a\' found $count times\n"; }

    The scalar form of grep returns the count of "matches" - not just a "true" value.
    I think that is the main point that you missed.

    If @arr contains multiple words, then I'm not know what you mean by a "match". I just trimmed the leading and trailing spaces from $a. If you have things in @arr like "Bob and Mary", and you want that to match across lines in @text, that is different too. But this will find " Bob and Mary " in an single line.

    Your requirement is not well specified. Better would be to show some input and desired output.

Re: REGEX:getting the count of occerence
by Anonymous Monk on Jan 02, 2012 at 07:27 UTC