I saw this in a piece of code:
if (some_condition) {
$index++;
}
$index{$some_variable} = $index{$some_variable} + 1;
What does $index{$some_variable}
mean? And why is it used?
Thank you.
EDIT:
index is defined as $index=0;
I saw this in a piece of code:
if (some_condition) {
$index++;
}
$index{$some_variable} = $index{$some_variable} + 1;
What does $index{$some_variable}
mean? And why is it used?
Thank you.
EDIT:
index is defined as $index=0;
If this code is written correctly, you will have these lines above it:
use strict;
use warnings;
my $index;
my %index;
if (some_condition) {
$index++;
}
$index{$some_variable} = $index{$some_variable} + 1;
$index{$some_variable}
is referring to a hash, and $index
to a scalar. In perl, this is perfectly valid, and %index
and $index
will be considered two different variables.
This is also a reason why it is so important to use strict. Why use strict and warnings?
It's retrieving an entry in the %index
hash using a key whose value is the value of $some_variable
(Note: There may also exist a scalar named $index
but it will occupy a separate namespace. That is, you can have both a hash and a scalar named index
and they will not conflict.)
Perl has several namespaces
$var
is a scalar variable@var
is an array variable, and $var[$i]
is an element of that array.%var
is a hash variable, and $var{$i}
is an element of that hash.The $index
in the $index++;
statement is a scalar. It has nothing to do with the $index{$some_variable}
statement that follows it.
The $index{$some_variable}
is part of a hash, %index
. Hashes (or associative arrays) consist one or more pairs, each pair consisting of a key and a value. The key is used to access the value.:
my %hash = ( key_A => value_A, # Here $hash{key_A} accesses 'value_A'
key_B => value_B, # ... $hash{key_B} gives 'value_B'
key_Z => value_Z ); # 'value_Z' returned by $hash{key_Z}
Analyzing $index{$some_variable} = $index{$some_variable} + 1;
, the value of $index{$some_variable}
is accessed, incremented by one and reassigned to the same key.
See perldoc perlintro
for a gentle introduction to variable types in Perl, and perldoc perldsc
for more complex data structures.