2

If I have an array, say @test and refer to items in the array as $test[0], etc. how should a my statement look? one of the following?

my (@test,$test); # array and element
my (@test); #just the array
my ($test);
2

2 Answers 2

5

If you just want the array, you only need to declare the array:

my @test;

When perl sees $test[0], it knows that it's a single-element access to the array @test.

The declaration for my $test would be for the completely separate scalar variable that has nothing to do with the array.

4

All three are possible. With only one variable, the parentheses aren't needed. Also, it's usually not a good idea to use the same name for different types of variables (an array and a scalar). $test[0] is the first element of @test, it has no relation to a scalar variable $test - but to prevent confusion, it's better not to use the same name.

Also, when declaring scalars and arrays, it's better to start with the scalars, so you can actually populate the variables.

my ($test, @tests);  # Better naming. Parentheses needed.
my @tests;           # Declares an array.
my $test;            # Declares a scalar, not related to any array.

my ($one, @rest) = 'a' .. 'z';  # Populates both the scalar and the array.
my (@all, $last) = 'a' .. 'z';  # !! Populates just the array.

Not the answer you're looking for? Browse other questions tagged or ask your own question.