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

what's the difference between:
my @array = (); and my @array; and my %hash = (); and my %hash;

Replies are listed 'Best First'.
Re: initialize arrays and hashes
by BrowserUk (Patriarch) on Aug 29, 2013 at 15:07 UTC
    what's the difference

    Absolutely nothing! (Say it again. :)

    C:\test>perl -MDevel::Peek=Dump -E"my %h; Dump \%h; my %i=(); Dump \%i +;" SV = RV(0x9ecb8) at 0x9eca8 REFCNT = 1 FLAGS = (TEMP,ROK) RV = 0x2e7590 SV = PVHV(0x2cd310) at 0x2e7590 REFCNT = 2 FLAGS = (PADMY,SHAREKEYS) ARRAY = 0x0 KEYS = 0 FILL = 0 MAX = 7 RITER = -1 EITER = 0x0 SV = RV(0x9ecb8) at 0x9eca8 REFCNT = 1 FLAGS = (TEMP,ROK) RV = 0x2e7608 SV = PVHV(0x2cd338) at 0x2e7608 REFCNT = 2 FLAGS = (PADMY,SHAREKEYS) ARRAY = 0x0 KEYS = 0 FILL = 0 MAX = 7 RITER = -1 EITER = 0x0

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: initialize arrays and hashes
by Eily (Monsignor) on Aug 29, 2013 at 15:02 UTC

    From a data point of view, none.

    From a reader / programmer point of view, in one case you have explicitly empty elements, in the other it's implied and the focus is on declaration of the variable and its scoping. You could for example use the first syntax as a reminder that your container might still be empty by the end, and the second when you are just defining the variable to give a specific scope, but the data has to be found somewhere else.

Re: initialize arrays and hashes
by davido (Cardinal) on Aug 29, 2013 at 16:50 UTC

    Perl, unlike C, C++, and other "pay only for what you use" languages, always automatically initializes scalar variables to "undef", or in the case of container variables, to the empty list. In a "Do what I mean" and "autovivification" language like Perl, it just seems to work better that way.


    Dave