Path: utzoo!mnetor!tmsoft!torsqnt!jarvis.csri.toronto.edu!cs.utexas.edu!usc!elroy.jpl.nasa.gov!jpl-devvax!lwall From: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Newsgroups: comp.lang.perl Subject: Re: Passing scalars by reference Message-ID: <7293@jpl-devvax.JPL.NASA.GOV> Date: 6 Mar 90 18:23:48 GMT References: <1220@frankland-river.aaii.oz.au> Reply-To: lwall@jpl-devvax.JPL.NASA.GOV (Larry Wall) Organization: Jet Propulsion Laboratory, Pasadena, CA Lines: 44 In article <1220@frankland-river.aaii.oz.au> pem@frankland-river.aaii.oz.au (Paul E. Maisano) writes: : Could someone please tell me how I can pass scalars by reference in the : same way arrays are. I know I can refer to $_[nnn] like its says in the : manual, but I would like to do something like: : : sub foo { : local($x_by_ref_with_meaningful_name) = $_[0]; : ... : $x_by_ref_with_meaningful_name .= $foo; # update the original scalar : } : : I tried this and it seemed to work on the first call only. Thereafter : it updated a global variable called $x_by_ref_with_meaningful_name. That won't do what you want, because local($scalar) = @_ will always copy the value--it's how you turn call-by-reference into call-by-value in Perl. There are several ways for you to reference the original scalar: 1) Give up on giving a meaningful name and refer to $_[0]. 2) Invoke the C preprocessor and say #define meaningful_name _[0] 3) Use the type glob *name to pass in the symbol name: sub foo { local(*meaningful_name) = $_[0]; $meaningful_name .= pop(@meaningful_name); } &foo(*original_name); This last method is the most powerful, because you can pass anything that has a name in the symbol table, including filehandles, subroutines and formats. What you're really doing is passing in the symbol table entry for everything with that name and giving it a new name locally. Note that mechanism 1 can only give you references into an array's elements, while mechanism 3 can give you the array as a whole, so you can push, pop, shift, etc. on it. Larry