-1

I am thinking how you can refer to an element in Perl array by the sign $.

Minimum code

my @x = @{ $_[0] }; 

for(my $i=0; $i<$#x; $i++){
    print $x[$i]; 
} 

You initialize the array as @x that is an array. You print out each item from the array by $x[$i] in a for loop.

I think it is a bit confusing when you initialize the array by @x and get its size by $#x.

Why can you refer to the Perl array by $x?

Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
  • 1
    ***`$#x`*** is ***NOT*** the size of the array. It is the index of the last element of the array. The size of the array is `@x` evaluated in scalar context. Also, `my $x = shift; print $x->[$_] for 0 .. $#$x;` to print the elements of the array without creating a copy. – Sinan Ünür May 14 '15 at 15:09
  • @SinanÜnür So the index can be something else than scalar in Perl. Right? – Léo Léopold Hertz 준영 May 14 '15 at 15:11
  • Indexing imposes scalar context. When you write `$ary[ ... ]` whatever is between `[ ]` is evaluated in scalar context. For example, `$ary[ @ary ]` will ***always*** be `undef` thanks to autovivification. In C, it would access an out-of-bounds memory location and lead to undefined behavior. – Sinan Ünür May 14 '15 at 15:12
  • @SinanÜnür So `$#x` should correspond to the size of the array through the last element of the array. Any cases where gaps in numbering? Possible? – Léo Léopold Hertz 준영 May 14 '15 at 15:13
  • 1
    `$#x` is the last index --- ***NOT THE SIZE OF THE ARRAY***. I don't know how much clearer this can be made. – Sinan Ünür May 14 '15 at 15:15

2 Answers2

2

Because the perlish way is to have the sigil denoting the type of thing you're working with, rather than being part of the variable name.

$x is a scalar, unrelated to the list @x. However $x[1] is still a scalar - but it's an element from the list @x. (and is unrelated to $x, because clearly - you couldn't pick a single element out of a single element).

$#x is a single value (scalar) so has the $ prefix still.

The same applies to hashes. %hash is the whole hash. $hash{$key} is a single value from that hash. And @hash{@some_keys} is a list of values from that hash.

Sobrique
  • 52,974
  • 7
  • 60
  • 101
1

You're not referring to the array with $x, you're referring to an element of the array with it. Your array is an array of scalar values which you use $ to access.

Please see the perlintro and perldata documentation. It'll cover the "why" of your question.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115