Grouping and Alternation

Learn about grouping and alternation in Perl.

We'll cover the following...

Grouping

Previous examples have all applied quantifiers to simple atoms. We may apply them to any regex element:

Perl
use Test::More;
my $pork = qr/pork/;
my $beans = qr/beans/;
like 'pork and beans', qr/\A$pork?.*?$beans/,
'maybe pork, definitely beans';
done_testing();

If we expand the regex manually, the results may surprise us:

Perl
use Test::More;
my $pork_and_beans = qr/\Apork?.*beans/;
like 'pork and beans', qr/$pork_and_beans/,
'maybe pork, definitely beans';
like 'por and beans', qr/$pork_and_beans/,
'wait... no phylloquinone here!';
done_testing();

Sometimes, specificity helps pattern accuracy:

Perl
use Test::More;
my $pork = qr/pork/;
my $and = qr/and/;
my $beans = qr/beans/;
like 'pork and beans', qr/\A$pork? $and? $beans/,
'maybe pork, maybe and, definitely beans';
done_testing();

Alternation

Some ...