perl - $dummy 和 non-parameter split 在 Perl 中是什么意思?

标签 perl split classification dummy-data

我需要一些帮助来解码这个 perl 脚本。 $dummy 在脚本的其他任何地方都没有用任何东西初始化。脚本中的以下行是什么意思?为什么 split 函数没有任何参数?

($dummy, $class) = split;

该程序试图使用某种统计分类方法来检查一个陈述是真实的还是谎言。所以假设它计算并给出以下数字给“truth-sity”和“falsity”,然后它检查测谎仪是否正确。

# some code, some code...
$_ = "truth"
# more some code, some code ...

$Truthsity = 9999
$Falsity = 2134123

if ($Truthsity > $Falsity) {   
    $newClass = "truth";      
} else {
    $newClass = "lie";     
}

($dummy, $class) = split;

if ($class eq $newClass) {
    print "correct";
} elsif ($class eq "true") {
    print "false neg";
} else {
    print "false pos"
}

最佳答案

($dummy, $class) = split;

Split 返回一个值数组。第一个放入 $dummy,第二个放入 $class,任何其他值都将被忽略。第一个 arg 可能命名为 dummy,因为作者计划忽略该值。更好的选择是使用 undef 来 忽略返回的条目:( undef, $class ) = split;

Perldoc 可以向您展示 split 的功能。当不带参数调用时,split 将针对 $_ 进行操作并根据空格进行拆分。 $_ 是 perl 中的默认变量,可以将其视为隐含的“它”,由上下文定义。

使用隐含的 $_ 可以使短代码更简洁,但在较大的 block 中使用它是一种糟糕的形式。您不希望读者对您要使用的“它”感到困惑。

split ;                      # split it
for (@list) { foo($_) }      # look at each element of list, foo it.
@new = map { $_ + 2 } @list ;# look at each element of list, 
                             # add 2 to it, put it in new list
while(<>){ foo($_)}          # grab each line of input, foo it.

perldoc -f 拆分

If EXPR is omitted, splits the $_ string. If PATTERN is also omitted, splits on whitespace (after skipping any leading whitespace). Anything matching PATTERN is taken to be a delimiter separating the fields. (Note that the delimiter may be longer than one character.)

我是三元运算符 的忠实粉丝? : 用于设置字符串值并将逻辑插入 block 和子例程。

my $Truthsity = 9999
my $Falsity   = 2134123

print test_truthsity( $Truthsity, $Falsity, $_ );

sub test_truthsity {
  my ($truthsity, $falsity, $line ) = @_;
  my $newClass = $truthsity > $falsity ? 'truth' : 'lie';
  my (undef, $class) = split /\s+/, $line ;

  my $output = $class eq $newClass ? 'correct' 
             : $class eq 'true'    ? 'false neg'
             :                       'false pos';
  return $output;
}

此版本中可能存在细微错误。没有参数的 splitsplit(/\s+/, $_) 不完全相同,如果行以空格开头,它们的行为会有所不同。在完全限定的拆分中,返回空白的前导字段。没有参数的 split 会删除前导空格。

$_ = "  ab cd";
my @a = split             # @a contains ( 'ab', 'cd' );
my @b = split /\s+/, $_;  # @b contains ( '', 'ab', 'cd')

关于perl - $dummy 和 non-parameter split 在 Perl 中是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8540132/

相关文章:

regex - Perl 条件正则表达式提取

xml - 如何替换 XML 属性名称值

jsp - 如何在JSTL中正确分割字符串?

math - 分割贝塞尔曲线

perl - 哪个脚本初始化模块?

python - 根据大小分割文件的有效方法

C# 在每个 # 符号后拆分字符串

machine-learning - 朴素贝叶斯和逻辑回归的假设

python - 如何使用 Keras 确定类别?

python - 将 NumPy 数组矢量化重新标记为连续数字并检索回来