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

Hi Monks,
I am sure this question has been raised in the past. I am (re)posting this question hoping to achieve the same with a oneliner. Below is a code snippet that I tried for counting the number of occurrences of a pattern in a file. I am interested in a perl oneliner to get the same result.
use strict; { local $/ = '\n'; while (<DATA>) { my $count = () = $_ =~ /XY[0-9]+/g; print "$count\n"; } } __DATA__ 22601571,XY12273,XY18561,XY19079,XY20765,XY18924 148986884,XY18644,XY18756,XY17986,XY19453,XY19121
Here is a reference to what I tried so far:
Update: http://www.codecodex.com/wiki/Count_the_number_of_occurrences_of_a_specific_character_in_a_string

Replies are listed 'Best First'.
Re: count the number of occurrences of a pattern in a file
by almut (Canon) on Apr 20, 2010 at 16:53 UTC
    $ perl -nle '$count++ while /XY[0-9]+/g; END {print $count}' inputfile

    (not what your code does, but what you ask for in the subject line)

      A very slight variation, not sure if yours is clearer in meaning than mine.

      perl -nle '$count += () = /XY[0-9]+/g; END {print $count}' inputfile

      Cheers,

      JohnGG

Re: count the number of occurrences of a pattern in a file
by kennethk (Abbot) on Apr 20, 2010 at 16:56 UTC
    This was discussed yesterday in Write code using less lines and is a FAQ. The one-liner might look like:

    ~/sandbox$ perl -pe '$_=()=/XY[0-9]+/g;$_.="\n"' junk.txt 5 5

    Note of course that your posted code would fail (single quotes don't interpolate so you are splitting on literal backslashes) and your link is broken. I've attempted to replicate your code's intended behavior (outputting new-line separated counts) rather than your stated goal (total occurrence in file).

Re: count the number of occurrences of a pattern in a file
by Anonymous Monk on Apr 20, 2010 at 16:49 UTC
    Single quotes do not interpolate, double quotes do interpolate (\n becomes a newline only in double quotes, aka interpolation). perlintro