[comp.lang.perl] when is pass by reference necessary?

pem@yarra-glen.aaii.oz.au (Paul E. Maisano) (03/28/91)

Consider this program:
(don't run it unless you need a file called file.dat in the current dir.)

#!/usr/bin/perl

($debug = 1, shift) if $ARGV[0] eq '-d';

sub my_open {   # called with (file_handle, name) 
    local(*F, $name) = @_;
    if ($debug) {
	open(F, ">&STDOUT") || die "can't dup STDOUT: $!\n";
    }   
    else {
	open(F, ">$name") || die "open $name: $!\n";
    }   
}

# should this be: &my_open(*X, "file.dat");
&my_open(X, "file.dat");
print X "hello world\n";
close(X);


When I wrote this, I intended to pass the file handle as *X but I forgot
the *. It still worked so I wondered if I was confused about why I thought
the * was necessary. Is it necessary ? 

---
Paul Maisano,
Australian Artificial Intelligence Institute

merlyn@iwarp.intel.com (Randal L. Schwartz) (03/29/91)

In article <1991Mar28.053132.7061@yarra-glen.aaii.oz.au>, pem@yarra-glen (Paul E. Maisano) writes:
| When I wrote this, I intended to pass the file handle as *X but I forgot
| the *. It still worked so I wondered if I was confused about why I thought
| the * was necessary. Is it necessary ? 

What's happening is that the 'X' is being passed as a literal string,
as if you had said

	&my_open("X", "file.dat");

and then in the assignment within the subroutine:

	local(*F, $name) = @_;

you are assigning:

	*F = "X";

which is the same as:

	*F = *X;

except that the "X" is looked up at runtime.  So, it is *safe* (at
least in this case... don't overgeneralize!), but *inefficient*.

print join(" ",("Perl","another","Just","hacker,")[2,1,0,3])
-- 
/=Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095 ==========\
| on contract to Intel's iWarp project, Beaverton, Oregon, USA, Sol III      |
| merlyn@iwarp.intel.com ...!any-MX-mailer-like-uunet!iwarp.intel.com!merlyn |
\=Cute Quote: "Intel: putting the 'backward' in 'backward compatible'..."====/