Consequetive pattern match in Perl

Tuesday, May 07, 2013 , 0 Comments

Make a pattern that will match three consecutive copies of whatever is currently contained in $what. That is, if
$what="fred" , your pattern should match "fredfredfred".
$what is "fred|barney", your pattern should match
"fredfredbarney" and
"barneyfredfred" and
"barneybarneybarney" and  many other variations.
Well, This is quite tricky. But the magic match to do over here is :

 Below is the example code:
use warnings;
use strict;
# notice the example has the `|`. Meaning
# match "fred" or "barney" 3 times.
my $str = 'fred|barney';
my @tests = qw(fred fredfredfred barney barneybarneybarny barneyfredbarney);
for my $test (@tests) {
if( $test =~ /^($str){3}$/ ) {
print "$test matched!\n";
} else {
print "$test did not match!\n";

Below is the execution:
> ./
fred did not match!
fredfredfred matched!
barney did not match!
barneybarneybarny did not match!
barneyfredbarney matched!