When there is nothing that references a data structure, it will go away. You can't access it, so it's not needed anymore.

Consider this: my $array = [1,2,3];

$array is a scalar -- it is a reference to the anonymous array created with [1,2,3]. It'll have an internal name like ARRAY(0x80cb8fc) or something, which is what is put in $array: try printing it, you'll see a string like that.

This is called a reference, it is magic. You can't just assign $array = "ARRAY(0x80cb8fc)"; and expect it to behave like a reference. It'll be just another string this way.

You can however, say:

my $array = [1,2,3]; my $alias = $array; $alias->[2] = 4; print $array->[2]; # Will produce 4.

In this example, both $array and $alias point to the same anonymous array.

You can also say something like:

my @array = (1,2,3); my $arrayref = \@array; print @$arrayref;
Which will print the contents of the array.

I recommend you read the References tutorial for more information.

The [1,2,3] array is anonymous, since it never gets a name. The reference to it, $array, has a name, but that's not the name of the array itself.

You'll want to use things like this for building e.g. a two-dimensional array, or an array of hashes, or a hash of arrays.


In reply to Re: Anonymous Data Structures: How Do They Work? by orkysoft
in thread Anonymous Data Structures: How Do They Work? by jonjacobmoon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.