列表快捷键:qw 引号空格运算符

在Perl中构建一组文字引号的列表的常见方法之一是使用引号空格运算符(qw)。它简洁、灵活且优雅。要了解为什么,让我们看看一个使用字符串列表的典型语句。

# import the Encode module and three subroutines
use Encode ('decode', 'encode', 'find_encoding');

在Perl中定义字符串列表时,我们必须用撇号将每个字符串括起来,用逗号分隔,并用括号包围。这有很多冗余,也容易出错,例如在使用引号(“)时需要撇号。而不是这样做,我们可以使用引号空格运算符。

use Encode qw/decode encode find_encoding/;

引号空格运算符接受一个列表分隔符,后跟由空格分隔的普通字符串列表,并返回一组文字引号字符串。分隔符可以是ASCII符号(斜杠/是一个流行的选择),括号或括号。让我们回顾一些更多例子。

# assign a list of an array
my @ny_boroughs = qw{Bronx Brooklyn Manhattan Queens Staten_Island};

# Quote some tricky symbols using tilde as the list delimiter
my @ascii_symbols = qw~! @ $ % ^ & * ( ) - _ = + { } [ ] \ | / ? ~;

# Use qw an input to a loop
foreach my $firm (qw/Deloitte ErnstAndYoung KPMG PWC/){
    print $firm; 
}

# It will ignore spaces, even double or triple spaces
my @colours = qw(red  blue   yellow    pink   green   ); 
foreach (@colours) {
    print $_;
}
# red
# blue
# yellow
# pink
# green

使用引号空格运算符通常会产生更干净、更简单的语法,从而降低了在处理列表时出错的风险。


本文最初发布在 PerlTricks.com

标签

David Farrell

David是一位专业程序员,他经常 推文博客 关于代码和编程艺术。

浏览他们的文章

反馈

这篇文章有什么问题吗?请在 GitHub 上打开一个问题或拉取请求来帮助我们。