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

I am currently working on a shoppingsystem that uses MySQL to handle the product database. I have writen a function that fetches the rows that where selected out of the MySQL database and puts it into an array. The function gets a referance to the array where the information is to be stored. And now comes the problem. if I declare the array using my() the function doesn't put anything in it, but if I use local() instead the function works perfectly. Why?

Code example:
my (@array);
or
local (@array);
...
&db_fetchdata(*array);


// Martin

Replies are listed 'Best First'.
Re: my() and local()
by davorg (Chancellor) on Aug 03, 2000 at 13:46 UTC

    You're not passing your function a reference to an array, but a typeglob. Under Perl 4 and earlier this was the only was to simulate passing by reference, but with Perl 5 you can take a reference to an array using \@array. Of course, you may need to change what's inside your function too.

    As for why my doesn't work - my creates a lexical variable which doesn't live in a typeglob, therefore you're not passing the 'right' @array variable into your function. You're passing the package variable @main::array.

    Liberal use of -w and use strict would have pointed out some of these problems to you.

    --
    <http://www.dave.org.uk>

    European Perl Conference - Sept 22/24 2000, ICA, London
    <http://www.yapc.org/Europe/>
RE: my() and local(), difference?
by mrmick (Curate) on Aug 03, 2000 at 17:50 UTC
    I think I'm re-phrasing part of what Davorg has above. If so, then it's simply to make it a little clearer to those of us who aren't quite at his level.

    :-)

    When you 'my' a variable, it is created/stored outside of the package's symbol table. This is why you can't see it when using a typeglob. A typeglob only gives us what is in the symbol table.

    Why not try a reference to the array to see if that will work for you?

    Mick