Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re^3: Small troubles with references

by swkronenfeld (Hermit)
on Feb 09, 2006 at 20:29 UTC ( #529187=note: print w/replies, xml ) Need Help??


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

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://529187]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2022-12-06 01:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?