在Perl中引用几乎任何奇怪的字符串都很简单。
my $url = q{http://my.url.com/any/arbitrary/path/in/the/url.html};
实际上,Perl中的各种引用机制非常有趣。Perl正则表达式般的引用机制允许您引用任何东西,并指定分隔符。您可以使用几乎任何特殊字符,例如#,/或开放/关闭字符,例如(),[]或{}。 例如:
my $var = q#some string where the pound is the final escape.#;
my $var2 = q{A more pleasant way of escaping.};
my $var3 = q(Others prefer parens as the quote mechanism.);
引用机制:
q:字面引用;只有结束字符需要转义。
qq:解释引用;处理变量和转义字符。非常适合需要引用的字符串。
my $var4 = qq{This "$mechanism" is broken. Please inform "$user" at "$email" about it.};
qx:与qq类似,但以非交互方式执行它作为系统命令。返回从标准输出生成的所有文本。(重定向,如果在操作系统中支持,也将一并返回)。此功能也可以使用反引号(`字符)实现。
my $output = qx{type "$path"};
my $moreout = qx{type "$path" 2>&1};
qr: 将 qq 格式的正则表达式解释并编译为正则表达式。同时支持正则表达式的各种选项。现在你可以将正则表达式作为变量传递:
sub MyRegexCheck {
my ($string, $regex) = @_;
if ($string)
{
return ($string =~ $regex);
}
return;
}
my $regex = qr{http://[\w]\.com/([\w]+/)+};
@results = MyRegexCheck(q{http://myurl.com/subpath1/subpath2/}, $regex);
qw:一个非常非常有用的引用操作符。将由空格分隔的引用词语转换为列表。在单元测试中填充数据非常好用。
my @allowed = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z { });
my @badwords = qw(WORD1 word2 word3 word4);
my @numbers = qw(one two three four 5 six seven);
my @list = ('string with space', qw(eight nine), "a $var");
my $arrayref = [ qw(and it works in arrays too) ];
每当它能使事情更加清晰时,它们都很好用。对于qx、qq和q,我最有可能使用{}运算符。人们最常使用qw的习惯通常是()运算符,但有时你也会看到qw//。