Why does Perl complain “Use of implicit split to @_ is deprecated”?

删除回忆录丶 提交于 2019-12-17 16:09:14

问题


This code triggers the complaint below:

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

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

When I run the code, Perl complains that "Use of implicit split to @_ is deprecated" . I really have no "context" for the problem, so I expect you help to explain what's wrong with the code.


回答1:


You are using split in scalar context, and in scalar context it splits into the @_ array. Perl is warning you that you may have just clobbered @_. (See perldoc split for more information.)

To get the number of fields, use this code:

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

or

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

Note: The three-argument form of split() is necessary because without specifying a limit, split would only split off one piece (one more than is needed in the assignment).




回答2:


Let diagnostics provide more information:

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;

Use of implicit split to @_ is deprecated

(D deprecated, W syntax) It makes a lot of work for the compiler when you clobber a subroutine's argument list, so it's better if you assign the results of a split() explicitly to an array (or list).

A better way to get diagnostic info is from the command line:

perl -Mdiagnostics my_program.pl



回答3:


From the split docs:

In scalar context, returns the number of fields found. In scalar and void context it splits into the @_ array. Use of split in scalar and void context is deprecated, however, because it clobbers your subroutine arguments.

So, since you're using it in scalar context, it splits into the @_ array, which is a deprecated usage. (It has to do the split though, since it'd break old code expecting it to split into @_ - no way around the warning without assigning into a temporary array, as far as I know. Eugene Y has this explicitly in his answer.)



来源:https://stackoverflow.com/questions/2436160/why-does-perl-complain-use-of-implicit-split-to-is-deprecated

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!