in reply to Why use references?

You also might want to modify an arg to a subrutine. E.G.
With References
sub increment { my $arg_ref = shift; $$arg_ref++; if (is_bad($$arg_ref)) { return "FAILURE!"; } return undef; } my $num = 0; my $err; $err = increment(\$num); if ($err) { die $err; } print "$num\n";
Without References
sub increment { my $arg = shift if (is_bad($arg)) { die "FAILURE"; } return ++$arg; } my $num = 0; $num = increment($num); print "$num\n";

I don't think my sub that uses references is any better than the one that doesn't. It just shows two ways of doing the same thing.

Because you pass $num as a reference, the subrutine can change num. Then you can use the function's return for something else.

Update: chas! I've fixed the example to use ++$arg rather than $arg++.

AND! Woah. Baked my noodle with that one. So the only reason I've been convinced that subrutine args were passed as values was because I was using shift all the time!? Man... aye aye aye...

Replies are listed 'Best First'.
Re^2: Why use references?
by chas (Priest) on Dec 12, 2005 at 01:55 UTC
    In your "Without References" example, don't you need  return ++$arg;?
    (and a semicolon after shift?)
    Also, consider the following:
    sub increment { ++$_[0]; } $num=0; increment($num); print $num,"\n";
    which shows that args are passed "by reference" by default. Of course, it may not be good style to alter @_ in this way, but the point is that you don't need to pass a reference to alter the argument inside the sub.
    (Updated to make less confusing.)