Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

slice

perl

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.

like image 655
tshepang Avatar asked Mar 14 '11 11:03

tshepang


2 Answers

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.

like image 77
toolic Avatar answered Oct 11 '22 14:10

toolic


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];
like image 26
Nikhil Jain Avatar answered Oct 11 '22 14:10

Nikhil Jain