in reply to Why use references?
Most of the responses concern themselves with references to arrays and hashes, except for pileofrogs who deals with scalar references in the context of passing arguments to procedures, but I don't know that it really explained what the advantage was.
These days, you can't assume that someone has already had C, and had already wrapped their head around pointers -- basically, in the example you gave, $int2 contains the location in memory to $int ... which allows us to modify the original variable, even when the original isn't in scope to be modified:
sub pass_by_value { my $value = shift; print $value++, "\n"; } sub pass_by_reference { my $ref = shift; print $$value++, "\n"; } my $x = 0; pass_by_value($x) for ( 1 .. 5 ); pass_by_reference(\$x) for ( 1 .. 5 );
Now, with something that simple, you can just return it from the function, and Perl allows you to easily return more than one item from a function, but for some people, this style just makes more sense.
For other times, we can use the reference as an alias to a value that we want to track, but we still want the variable to keep its original identity:
foreach my $pair ( [9,5],[0,3],[6,8],[8,3] ) { my ($a, $b) = @$pair; my $min = ($a < $b) ? \$a : \$b; # do whatever with the minimum ... $$min += 2; # changes are then reflected in $a or $b print "$a ; $b\n"; }
These are rather simplistic examples, and don't really show the full power of what you can do with scalar references. As you're starting out in programming, you'll probably never need to use them -- in fact, until you start to use them, and start thinking about where they'll save you time and effort, they're probably more pain than they're worth as you get confused and try to assign values directly to the reference, and have to track down your errors.
|
|---|