Path: utzoo!attcan!uunet!cs.utexas.edu!samsung!munnari.oz.au!frankland-river!pem From: pem@frankland-river.aaii.oz.au (Paul E. Maisano) Newsgroups: comp.lang.perl Subject: Creating a reference to an array index Message-ID: <1361@frankland-river.aaii.oz.au> Date: 17 Mar 90 14:48:06 GMT Organization: Australian AI Institute Lines: 61 A short while ago I posted a request to see if anyone could think of a way I could generate a reference to a particular index of an array. For scalars it is easy; I have used code like the following to parse command line args. The effect is: 'prog -p x y -u 1 2 -p z' results in $pvar == 'x y z ', $uvar == '1 2 ' while ($_ = shift) { /^-p$/ && (*vptr = *pvar, next); /^-u$/ && (*vptr = *uvar, next); $vptr .= "$_ "; } Anyway, if I have an array, say @ary = (1, 2, 3) I want to be able to get a reference to an element of that array, so that I can manipulate it independently of the array. Randal mentioned that a foreach might work as in (something like): foreach $x ($ary[1]) { # manipulate x and modify the array } The foreach will only have this effect when an actual array is passed to the foreach. So you can't really use this method. I mentioned that a grep would work as in the following: grep( do { # manipulate $_ and modify the array }, $ary[1] ); This has the draw back of not letting you name the variable to something meaningful. So in my search for neatness (or any kludge that would work) I came up with the following: grep(*vptr = *_, $ary[1]) # manipulate $vptr and modify the array It makes sense when you think about it. `_' contains the symbol table entry for the element of the array which we then assign to `vptr'. (Ok, ok, so I peeked at the source :-) Now I am content and can sleep again at nights. But I am too tired to work out how to generate "Just Another Perl Hacker," using it. Randal ? :-) Here's a test fragment: #!/usr/local/bin/perl @ary = (1, 2, 3); grep(*vptr = *_, $ary[1]); print "@ary\n"; # => 1 2 3 $vptr++; print "@ary\n"; # => 1 3 3 ------------------ Paul E. Maisano Australian Artificial Intelligence Institute 1 Grattan St. Carlton, Vic. 3053, Australia Ph: +613 663-7922 Fax: +613 663-7937 Email: pem@aaii.oz.au UUCP: {uunet,mcsun,ukc,nttlab}!munnari!aaii.oz.au!pem