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

Hi all!
I have been dealing for a 1/2 hour now with the following problem, and don't seem to be getting anywhere.
I have a string
$string_to_match='QWERTAAWAAAAKAAAAAAAA';';
I want to search the string above, starting from the end of the string, get the 17 characters that preceed the end and see how much 'A' I have. If I have more than 14 A in the 17 characters, then the match is succesful.
I go:
$check = substr($string_to_match, -17, 17); if ($check=~/A{14,17}/) {print "correct";}
The best part is that I INDEED have 14 occcurences of 'A' in the last 17 characters.. but it does not match... Please help me!

2006-05-28 Retitled by g0n, as per Monastery guidelines
Original title: 'This error is giving me a headache!!!'

Replies are listed 'Best First'.
Re: Count the number of matched characters
by borisz (Canon) on May 28, 2006 at 10:36 UTC
    You need to count the number of 'A'. Your code try to match 14..17 A without any other chars inbeetween.
    $string_to_match='QWERTAAWAAAAKAAAAAAAA'; if ( substr($string_to_match, -17) =~ y/A// >= 14 ) { print 'Correct'; }
    Boris
Re: Count the number of matched characters
by QM (Parson) on May 28, 2006 at 15:51 UTC
    I know borisz's y/// is better, but here's a regex TIMTOWTDI entry:
    $string_to_match='QWERTAAWAAAAKAAAAAAAA'; $check = substr($string_to_match, -17, 17); $count = () = ( $check =~ /(A)/g ); if ( $count >= 14) { print "correct"; }
    This uses the (undocumented?) ()= "operator" to force m///g to return a list of matches, which then gets converted to a count in $count = ().

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

Re: Count the number of matched characters
by ioannis (Abbot) on May 28, 2006 at 16:03 UTC
    Another way is to do this:
    () = substr($_,-17) =~ / A (?{ print 'yes' if $::i++>12}) /xg;