Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, what is the difference between @array[1] and $array[1]?

Tags:

arrays

perl

I have been studying array slices and frankly do not see the difference between choosing @array[1] and $array[1]. Is there a difference?

#!/usr/bin/perl 
@array = (1,3);
print "\nPrinting out full array..\@array\n";
print "@array\n";
print "\n";
print "Printing out \@array[1]\n";
print "@array[1]\n";
print "Printing out \$array[1]\n";
print "$array[1]\n";
print "\n\n";
like image 597
capser Avatar asked Oct 05 '11 07:10

capser


2 Answers

This is a FAQ.

The two forms are likely to work the same way in many contexts (but not all, as you can see from the example in the FAQ), but $array[1] expresses the intent more clearly.

like image 191
Keith Thompson Avatar answered Sep 27 '22 19:09

Keith Thompson


$ and @ are called sigils: hear what the sigils tell you

When you see $ you are dealing with a single thing. When you see @ you have a list of things.

@array[ 1 ] is a slice, a list with selected elements from the @array list. You have put only an element in this slice, the second element of @array, but it's a list anyway.

$array[ 1 ] is the second element of the list, a single value, a scalar.

@hash{ 'one', 'two' } is another kind of slice: this time we sliced an hash ( %hash ), obtaining a list with values corresponding to keys one and two.

Where's the difference? Although the difference is thin, you should avoid single element slices when you want a single value. Remember that on the right hand side of an expression, single element slices behave like scalars, but when they are on the left hand side of an expression they become a list assignment: they give list context to the expression.

If still you aren't feeling comfortable with the difference between scalar and list context, please don't use single element slices in order to avoid unexpected results in certain situations ( for instance when using the line input operator < > ).

Check the docs and happy Perl.

like image 45
Marco De Lellis Avatar answered Sep 27 '22 18:09

Marco De Lellis