The =~
operator attempts to match a regular expression (set apart by /
) to a string:
my $str = "hello world";
print "Hi, yourself!\n" if $str =~ /^hello/;
/^hello/
is the actual regular expression. The ^
is a special character that tells the regular expression to start with the beginning of the string and not match in the middle somewhere. Then the regex tries to find the following letters in order h
, e
, l
, l
, and o
.
Regular expressions attempt to match the default variable ($_
) if bare:
$_ = "hello world";
print "Ahoy!\n" if /^hello/;
You can also use different delimiters is you precede the regular expression with the m
operator:
m~^hello~;
m{^hello};
m|^hello|;
This is useful when matching strings that include the /
character:
print "user directory" if m|^/usr|;