arraysperlvariableselement

How do i use "my" to declare array and element in perl?


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);

Solution

  • 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.