in reply to Re: Small troubles with references
in thread Small troubles with references

So then what's the advantage (or disadvantage of) using/creating references?

Replies are listed 'Best First'.
Re^3: Small troubles with references
by swkronenfeld (Hermit) on Feb 09, 2006 at 20:29 UTC
    Other people did a great job of answering pass-by-reference vs. pass-by-value. But if your question here is: "Why would you pass things to a subroutine when you can just call them by their original name?" then read on:

    #!/usr/bin/perl -w use strict; sub1(); sub sub1 { my @arr1 = ("dog", "cow", "camel"); print indexOf(\@arr1, "cow"); } sub indexOf { my $aref = shift; my $element = shift; my $count=0; foreach (@$aref) { return $count if($_ eq $element); $count++; } #foreach (@arr1) { } # WRONG, @arr1 is not in scope }


    As you can see in this example, you can't always call an element in the subroutine by the name from the caller. The variable might not be in scope in the callee.

    A final note: I'm using pass-by-reference here because I'm not modifying the array in the indexOf() subroutine. Pass-by-reference is faster and less memory consuming than pass-by-value, but be careful that the subroutine you pass to doesn't modify your contents if you're expecting them preserved.