【问题标题】:Why does Perl complain "Use of implicit split to @_ is deprecated"?为什么 Perl 抱怨“不推荐使用对 @_ 的隐式拆分”?
【发布时间】:2011-01-27 00:40:24
【问题描述】:

此代码触发以下投诉:

#!/usr/bin/perl 
use strict;
use warnings;

my $s = "aaa bbb";
my $num_of_item = split(/\s+/, $s) ;
print $num_of_item;

当我运行代码时,Perl 抱怨说 "Use of implicit split to @_ is deprecated" 。 我真的没有这个问题的“背景”,所以我希望你能帮忙解释一下有什么问题 代码。

【问题讨论】:

  • 你确定你有完整的错误信息吗?我的 perl 还在第 6 行告诉我问题。由于拆分在第 6 行,阅读拆分文档会告诉我第二段中的问题。 :)

标签: perl


【解决方案1】:

您在标量上下文中使用split,在标量上下文中它拆分为@_ 数组。 Perl 警告你,你可能刚刚破坏了@_。 (有关更多信息,请参阅perldoc split。)

要获取字段数,请使用以下代码:

my @items = split(/\s+/, $s);
my $num_of_item = @items;

my $num_of_item = () = split /\s+/, $s, -1;

注意:split() 的三参数形式是必要的,因为如果没有指定限制,split 只会分割出一块(比需要的多一个) 任务)。

【讨论】:

  • 或者为了简洁,my $num_of_item = () = split(/\s+/,$s)
  • @mobrule: 你的评论来晚了:-)
  • 那个带有 () 的方法对我不起作用; $num_of_item 被设置为 1。
  • fwiw,如果你不使用 LIMIT 参数并且你的模式没有捕获,split /pattern/, $str 的计数将比 /pattern/ 匹配 @ 的次数多一987654330@,您可以通过 m//g 匹配找到它,而无需使用 split :)
  • @hobbs:实际上,此行为记录在手册页中:When assigning to a list, if LIMIT is omitted, or zero, Perl supplies a LIMIT one larger than the number of variables in the list, to avoid unnecessary work. 对于空列表,LIMIT 默认为 1。
【解决方案2】:

diagnostics提供更多信息:

use strict;
use warnings;
use diagnostics; # comment this out when you are done debugging

my $s = "aaa bbb";
my $num_of_item = split(/\s+/, $s) ;
print $num_of_item;

不推荐使用对@_ 的隐式拆分

(不推荐使用 D,W 语法) 你破坏了一个子程序的参数列表,所以最好分配 将 split() 的结果显式传递给数组(或列表)。

从命令行获取诊断信息的更好方法:

perl -Mdiagnostics my_program.pl

【讨论】:

  • use diagnostics 在收到您不理解的警告消息方面是一个真正的救星
  • @mobrule:您也可以在perldoc perldiag (perldoc.perl.org/perldiag.html) 中查找这些消息以获得更详细的说明。
【解决方案3】:

来自split 文档:

在标量上下文中,返回找到的字段数。在标量和 void 上下文中,它拆分为 @_ 数组。但是,不推荐在标量和 void 上下文中使用 split,因为它会破坏您的子例程参数。

因此,由于您在标量上下文中使用它,它会拆分为 @_ 数组,这是一种已弃用的用法。 (尽管它必须进行拆分,因为它会破坏旧代码,期望它拆分为@_ - 据我所知,如果不分配到临时数组,就无法绕过警告。尤金 Y 在他的回答。)

【讨论】:

    猜你喜欢
    • 2021-04-21
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2019-07-18
    • 2013-05-03
    • 2014-02-16
    相关资源
    最近更新 更多