What are the consequences of “$scalar = @array[n]”?

試著忘記壹切 提交于 2019-12-12 12:20:05

问题


use warnings;
my @array = (0, 1);
my $scalar1 = $array[0];
my $scalar2 = @array[0];
if($scalar1 == $scalar2) {
    print "scalars are equal\n";
}

Here's the output when I run /usr/bin/perl5.10.1 test.pl:

Scalar value @array[0] better written as $array[0] at test.pl line 4.
scalars are equal

I'm concerned about that warning.


回答1:


You can look up all warning messages in perldoc perldiag, which explains the consequences:

(W syntax) You've used an array slice (indicated by @) to select a single element of an array. Generally it's better to ask for a scalar value (indicated by $). The difference is that $foo[&bar] always behaves like a scalar, both when assigning to it and when evaluating its argument, while @foo[&bar] behaves like a list when you assign to it, and provides a list context to its subscript, which can do weird things if you're expecting only one subscript.

On the other hand, if you were actually hoping to treat the array element as a list, you need to look into how references work, because Perl will not magically convert between scalars and lists for you. See perlref.

Similarly, you can use diagnostics; to get this verbose explanation of the warning message.

A third way is to use the splain utility.




回答2:


It is possible to take an array slice of a single element:

@fruits[1]; # array slice of one element

but this usually means that you’ve made a mistake and Perl will warn you that what you really should be writing is:

$fruits[1];



回答3:


There are no consequences for that usage. I think the purpose is to help you avoid the consequences when a warning can't be issued.

Slices on the LHS of "=" cause =" to be a list assignment operator.

$ perl -E'sub f { return 4; } my $x = $a[1] = f(); say $x'
4

$ perl -E'sub f { return 4; } my $x = @a[1] = f(); say $x'
1

Slices evaluate the index in list context.

$ perl -E'sub f { my @i = 3; @i } @a=qw( a b c d e f ); say @a[f()]'
d

$ perl -E'sub f { my @i = 3; @i } @a=qw( a b c d e f ); say $a[f()]'
b


来源:https://stackoverflow.com/questions/5298208/what-are-the-consequences-of-scalar-arrayn

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