Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^2: Small troubles with references

by coldmiser (Hermit)
on Feb 09, 2006 at 19:50 UTC ( [id://529175]=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-04-18 19:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found