perl 逗号分隔变量块等于另一个逗号分隔值块
perl block of comma separated variables equals another block of comma separated values
我正在检查一个 perl 脚本,并在脚本顶部的几个地方遇到了如下代码:
(
$AllowFullYearView, $LevelForRobotsDetection,
$LevelForWormsDetection, $LevelForBrowsersDetection,
$LevelForOSDetection, $LevelForRefererAnalyze,
$LevelForFileTypesDetection, $LevelForSearchEnginesDetection,
$LevelForKeywordsDetection
)
= ( 2, 2, 0, 2, 2, 2, 2, 2, 2 );
这是什么意思?我的第一个想法是 shorthand 为变量设置值的方法,但是每个块中的元素数量不一样。
(试图描述结构使得搜索答案变得困难。)
这是一个赋值:左侧列表中的所有元素都被赋予了右侧列表中的值。这是按位置,左边列表中的元素1从右边列表中的元素1中获取值,依此类推。
#!perl
use strict;
use warnings;
my ($a, $b, $c) = (1, 2, 3);
print "a=$a, b=$b, c=$c\n";
这会打印:
a=1, b=2, c=3
现在当右侧列表的元素多于左侧列表时,不会使用多余的元素。
#!perl
use strict;
use warnings;
my ($a, $b, $c) = (1, 2, 3, 4, 5, 6);
print "a=$a, b=$b, c=$c\n";
仍然打印:
a=1, b=2, c=3
如果左边的列表有更多元素,则不会为多余的元素分配任何内容:
#!perl
use strict;
use warnings;
my ($a, $b, $c) = (1, 2);
print "a=$a, b=$b, c=$c\n";
Use of uninitialized value $c in concatenation (.) or string at lists.pl line 6.
a=1, b=2, c=
警告是由 use warnings;
引起的(每个程序都应该有)。
在您的情况下,如果列表大小不合适,则可能意味着有人调整了一个列表而忘记了另一个。
因此,更好的分配方式是单独执行:
my $AllowFullYearView = 2;
my $LevelForRobotsDetection = 2;
...
如果值缺失或多余,就会变得很明显。
复制列表通常用于函数中的参数:
sub foo {
my ($a, $b, $c) = @_;
...
}
此处 foo
函数将其前 3 个参数从 @_
数组复制到局部变量 $a
、$b
和 $c
。
我正在检查一个 perl 脚本,并在脚本顶部的几个地方遇到了如下代码:
(
$AllowFullYearView, $LevelForRobotsDetection,
$LevelForWormsDetection, $LevelForBrowsersDetection,
$LevelForOSDetection, $LevelForRefererAnalyze,
$LevelForFileTypesDetection, $LevelForSearchEnginesDetection,
$LevelForKeywordsDetection
)
= ( 2, 2, 0, 2, 2, 2, 2, 2, 2 );
这是什么意思?我的第一个想法是 shorthand 为变量设置值的方法,但是每个块中的元素数量不一样。
(试图描述结构使得搜索答案变得困难。)
这是一个赋值:左侧列表中的所有元素都被赋予了右侧列表中的值。这是按位置,左边列表中的元素1从右边列表中的元素1中获取值,依此类推。
#!perl
use strict;
use warnings;
my ($a, $b, $c) = (1, 2, 3);
print "a=$a, b=$b, c=$c\n";
这会打印:
a=1, b=2, c=3
现在当右侧列表的元素多于左侧列表时,不会使用多余的元素。
#!perl
use strict;
use warnings;
my ($a, $b, $c) = (1, 2, 3, 4, 5, 6);
print "a=$a, b=$b, c=$c\n";
仍然打印:
a=1, b=2, c=3
如果左边的列表有更多元素,则不会为多余的元素分配任何内容:
#!perl
use strict;
use warnings;
my ($a, $b, $c) = (1, 2);
print "a=$a, b=$b, c=$c\n";
Use of uninitialized value $c in concatenation (.) or string at lists.pl line 6. a=1, b=2, c=
警告是由 use warnings;
引起的(每个程序都应该有)。
在您的情况下,如果列表大小不合适,则可能意味着有人调整了一个列表而忘记了另一个。
因此,更好的分配方式是单独执行:
my $AllowFullYearView = 2;
my $LevelForRobotsDetection = 2;
...
如果值缺失或多余,就会变得很明显。
复制列表通常用于函数中的参数:
sub foo {
my ($a, $b, $c) = @_;
...
}
此处 foo
函数将其前 3 个参数从 @_
数组复制到局部变量 $a
、$b
和 $c
。