It seems a little odd to me to just change characters for something like that and expect perl to "know" that's what they are there for. Does it really work that way?
Yes, it does really work that way... more or less.
The one catch is that, when you use alternate delimiters, you have to explicitly use either "m" or "s" at the beginning of the regex. The "m" and "s" are the actual operators which (in the right context) trigger a regex operation, so when perl sees those followed by punctuation, it recognizes that the punctuation used will be the delimiter for that regex without needing to expicitly set or reset anything.
So, for example, all of these variations are equivalent:
#!/usr/bin/perl
use strict;
use warnings;
my $text = 'This is a text string.';
print $text =~ m/is a/, " - m//\n";
# Default delimiter, so the "m" can be omitted
print $text =~ /is a/, " - //\n";
# Custom delimiters, so the "m" is mandatory
print $text =~ m#is a#, " - m##\n";
print $text =~ m!is a!, " - m!!\n";
print $text =~ m^is a^, " - m^^\n";
# Open/close punctuation is used in pairs
print $text =~ m[is a], " - m[]\n";
print $text =~ m(is a), " - m()\n";
print $text =~ m<is a>, " - m<>\n";
The print on each regex displays the number of matches found along with the delimiters used:
1 - m//
1 - //
1 - m##
1 - m!!
1 - m^^
1 - m[]
1 - m()
1 - m<>
|