--- Bill Jones <[EMAIL PROTECTED]> wrote:
> References:
> 
> I am looking for a basic explaination and example:
> 
> $animal = "Dog";
> $sound  = \$animal;
> $bark   =  $$sound;
> 
> $bark is now Dog.
> 
> ???
> -Sx-

The following explanation is oversimplified, but I think it's easy to follow.

    $animal = "Dog";

That assigns the string "Dog" (without the quotes) to the scalar $animal.

    $sound = \$animal;

Putting a backslash in front of a variable (if the variable is not being interpolated 
in quotes)
will create a reference to that variable.  $sound is a reference.

    $bark   =  $$sound;

One way to dereference a variable is to prepend the proper variable symbol ($, @, or 
%) to the
variable that contains the reference.

One thing are good for is passing around large data structures.  For example:

    my %hash   = ( large amounts of data here );
    my $result = process_data( \%hash );

    sub process_data {
        my $hash_ref = shift;
        foreach my $key ( values %$hash_ref ) {
            my $value = $hash_ref->{ $key };
            # do stuff
        }
    }

In the above example, imagine that the hash had 10,000 key/value pairs.  By passing it 
as a
reference, you are only passing a simple scalar reference, instead of the 10,000 
pairs.  However,
you have to be careful with this technique.  Since you're passing a reference, the 
process_data()
subroutine is using the actual data in %hash, as opposed to a copy of the data.  Thus, 
if you
change that data, you're changing the original hash.  This snippet will demonstrate 
that:

    my $data = [ qw/ 1 2 / ];
    process( $data );
    print "@$data";

    sub process {
        my $array_ref = shift;
        $_++ foreach @$array_ref;
    }

Cheers,
Curtis "Ovid" Poe

=====
Senior Programmer
Onsite! Technology (http://www.onsitetech.com/)
"Ovid" on http://www.perlmonks.org/

__________________________________________________
Do You Yahoo!?
NEW from Yahoo! GeoCities - quick and easy web site hosting, just $8.95/month.
http://geocities.yahoo.com/ps/info1

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to