ginju75 has asked for the wisdom of the Perl Monks concerning the following question:

Hi If I define an array as:
my @x;
in a sub, do I need to specify 'my' to use an element of an array? as my $X[0]? Do I need that 'my' before the scalar element of an array that was defined as local using 'my'?? Thank you all. From a learning monk!

Replies are listed 'Best First'.
Re: Local Vs...
by chip (Curate) on Nov 30, 2001 at 05:53 UTC
    In addition to my esteemed brother's previous comment, I might suggest that you got the idea for my $x[0] from the idiom of local $x[0]. However, local is very very different from my, and you can't generally assume that either one can replace the other in any situation.

    BTW, the local operator is so confusingly named that Larry is renaming it to temp in Perl 6. And there was much rejoicing!

        -- Chip Salzenberg, Free-Floating Agent of Chaos

Re: Local Vs...
by ehdonhon (Curate) on Nov 30, 2001 at 04:34 UTC

    It depends. In the first case you used a lower-case x and in the second, you used an upper case X. They are not the same. Did you mean to do that?

    Assuming you meant those to be the same, the answer is that you do not have to delclare my on the second line. You have to define @x with my to tell perl that you are using lexical scoping. When you do something with $x[0], it already knows what scope it is in.

Re: Local Vs...
by davorg (Chancellor) on Nov 30, 2001 at 14:56 UTC

    You can't create a lexical variable that refers to a single element of an array. Did you try it? I get the following compilation error:

    Can't declare array element in my at ./test.pl line 5, near "];"
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you don't talk about Perl club."