7.6. Binding to the Beginning or the End of a String

In a regular expression a caret (^) at the beginning of the expression matches the beginning of the string and a dollar sign ($) at the end of the expression matches the end of the string.

For example, the following program checks if a string is composed entirely of the letter A:

use strict;
use warnings;

my $string = shift;

if ($string =~ /^[Aa]*$/)
{
    print "The string you entered is all A's!\n";
}
else
{
    print "The string you entered is not all A's.\n";
}

It's much shorter than with using a loop and also much faster.

Here's another example. Let's check if a string ends with three periods:

use strict;
use warnings;

my $string = shift;

if ($string =~ /\.\.\. *$/)
{
    print "The string you entered ends with an ellipsis.\n";
}
else
{
    print "The string you entered does not end with an ellipsis.\n";
}

Written by Shlomi Fish