in reply to Anonymous Data Structures

I had to look up anonymous data structures to figure out what you were referring to and it appears that they are just talking about references. THAT I can help you with.

Normally there are two ways of working with a variable, making a copy of it, or using a reference to it. A simplified example would be a sign-in sheet for a writing class. You want everyone to write their name on the sheet so you have to get information from everyone. There are two ways of doing this,

The first way sounds stupid, but you will be surprised how often it occurs, especially with beginners. Here is code to show how it works.

#!/usr/bin/perl use strict; use warnings; # Make a copy of a variable my $counter = 0; print "Copying and replacing the variable\n"; for (1..10) { $counter = increment_number( $counter ); print "Count is $counter\n"; } $counter = 0; print "Passing a reference to the variable\n"; for (1..10) { increment_number( \$counter ); print "Count is $counter\n"; } sub increment_number { my $number = shift; if (ref $number eq 'SCALAR') { $$number++; return; } return ++$number; }

Replies are listed 'Best First'.
Re^2: Anonymous Data Structures
by lwicks (Friar) on Jun 01, 2007 at 15:56 UTC
    Hi Herkum, So colour me a noob, but what you are saying is in your first example we are chewing up memory creating a copy of $counter. Whereas in the second example we are pointing to the original. The implication being that example two is more efficient/faster/leet? Is that right. Lance

    Kia Kaha, Kia Toa, Kia Manawanui!
    Be Strong, Be Brave, Be perservering!

      your first example we are chewing up memory creating a copy of $counter

      Correct.

      in the second example we are pointing to the original. The implication being that example two is more efficient/faster/leet? Is that right.

      Correct as well. The example I used does not really offer any performance benefits because it is too small.

      Lets supposed you have a million element array. In the first example you would, create 2 copies of that million element array in your program(So it takes more memory). You would also be passing million values to and from the function(so it would be slower).

      If you use a reference you have one copy of that array. You only passing a single value to the function. This can be provide enormous performances benefits when working with a large amount of data.

      There are times you want to make a copy because you don't want to change the original data. But if you are modifying the original values you should use references.