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.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With