0

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?

Jens
  • 67,715
  • 15
  • 98
  • 113
SSN
  • 846
  • 2
  • 7
  • 20

1 Answers1

5

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.

Community
  • 1
  • 1
simbabque
  • 53,749
  • 8
  • 73
  • 136
  • 2
    Is it really "old-fashioned"? Was that how it worked with really old versions of Perl? In the twenty years I've been using Perl it's always just been wrong :-) – Dave Cross Mar 01 '16 at 11:11
  • @dave I think you're right. It just didn't warn about it, I guess. I am trying to find some reference for that, as I think it might be a Perl 4 leftover, but it's really hard to find any documentation that old. – simbabque Mar 01 '16 at 11:18
  • @dave I think this will make it more clear. it's not wrong per se, it's just a different thing :) – simbabque Mar 01 '16 at 11:26