Damn I hate being publicly wrong, but you're right.

#!/usr/bin/perl -w
use strict;

my $a = 1;
foo($a);
print "$a\n";

sub foo {
  $_[0] = 2;
}


prints '2'.  It's shifting them off that list that creates the copy I am 
used to working with.

But it still remains true that passing $dbh is safe, even if you shift it 
off the list.

But I think we're officially off topic now.

____________________________
Jeff Seger
Fairchild Semiconductor
jeffrey.seger at fairchildsemi.com
____________________________




David <[EMAIL PROTECTED]>
01/10/2005 12:36 PM

 
        To:     Dbi-Users <dbi-users@perl.org>
        cc: 
        Subject:        Re: passing dbh


On Mon, Jan 10, 2005 at 12:28:44PM -0500, [EMAIL PROTECTED] 
wrote:
> I hate confusion, so I went to the source: perldoc perlsub, and here is 
> what it had to say:
> 
> The Perl model for function call and return values is simple: all 
> functions are passed as parameters one single flat
>        list of scalars, and all functions likewise return to their 
caller 
> one single flat list of scalars.  Any arrays or
>        hashes in these call and return lists will collapse, losing their 

> identities--but you may always use pass-by-reference
>        instead to avoid this.
> 
> In other words, perl passes arguments by copy, not reference.

This is not correct.  All the above says is that everything is passed as
a list.  While the list is flat, it actually contains references to the
elements of the list. 

For example:

  sub f { $_[0] = 1; }
  my $i = 0;
  &f($i);
  print("$i\n");

prints 1<new-line>.

You can avoid pass the effects of by reference by changing the
subroutine to work with copies:

  sub f { my ($n) = @_; $n = 1; }

> In other words, yes, it is safe to just say  "foo($dbh)" , but don't 
start 
> thinking that everytime you pass an argument to a subroutine that you 
are 
> passing a reference, because you are not unless you explicitly do so.

Passing arguments explicitly by reference is only useful is you want to
pass an array or hash as a single entity.

dd
-- 
David Dooling





Reply via email to