I have perl coding like this
@arr = qw(1 2 3 4);
print $arr[0],"\n";
print @arr[0],"\n";
Both output answer is 1 then, What is the difference? Is it any difference in memory storage?
I have perl coding like this
@arr = qw(1 2 3 4);
print $arr[0],"\n";
print @arr[0],"\n";
Both output answer is 1 then, What is the difference? Is it any difference in memory storage?
Using the @
sigil with an array element is using an array slice with a single element list. If you turn on use warnings
it will tell you:
scalar value @arr[0] better written as $arr[0] at foo.pl line 709
If you also use diagnostics
, it will explain quite a bit.
Scalar value @arr[0] better written as $arr[0] at foo.pl line 709 (#1)
(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.
So in general, you should use the sigil of the type of thing a variable call returns. For a single array element, that is scalar, so you use $
.
Using @
implies it returns a list. An array itself returns a list, and so does an array slice. Here you did a slice with one element. That is not a big problem, but also not the way it's intended, which is why Perl warns you about it.
Just use warnings
, and also use strict
(and declare your variables with my
), and always use the correct sigil.
Don't put use diagnostics
into your production code, as it slows everything down quite a bit. Just use it if you don't understand a warning.
Also see this answer by brian d foy.