Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.

In reply to Re^3: Small troubles with references by swkronenfeld
in thread Small troubles with references by coldmiser

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-23 23:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found