On 12/16/09 Wed Dec 16, 2009 6:57 AM, "Bryan R Harris" <bryan_r_har...@raytheon.com> scribbled:
> > > [stuff cut out] > >>> For example, if I'm populating a complex variable @d with >>> lots of pointers, >>> hashes, arrays, etc. within, if I populate that within a >>> subroutine, how do >>> I get it back out conveniently without it making a whole >>> nother copy of it >>> outside? If it's 500 MB, isn't that horribly inefficient? >>> Plus, I have to >>> keep track of it. >>> >> You pass as a refernce as ni >> called_sub(\...@d); >> Now when you update, you are updating @d and not a copy. >> >> If you have any questions and/or problems, please let me know. >> Thanks. >> >> Wags ;) >> David R. Wagner > > > So let's say I pass a reference to an array: > > my @d = (1,2,3); > called_sub(\...@d); > > ... but then in called_sub, accessing that gets a lot "noisier", right? > > sub called_sub { > my $d = shift; > push @{$d}, 2; # I'd rather be able to use @var instead of @{$var} > } As Shlomi pointed out, you can refer to the entire array as @$d. The largest index is $#$d. You can refer to elements using the $d->[0] syntax, which is equivalent to ${$d}[0]. If the array isn't too large, and you don't need to modify the original array, you can just make a copy and use that in the subroutine: my @copy = @$d; > > Is there any way to make a new variable, @something, that is just another > name for the array that was passed in by reference? Since I'm building a > complex data structure, having to include all those @{}'s can get annoying. Elements of a hash referenced by $h can be accessed by $h->{key}. Nested structures can sometimes be simplified: $h->{key1}->[key2} is a two-level nested hash, which can be simplified to $h->{key1}{key2}. The array-of-array element ${${$a}[2]}[3] can be written as $a->[2]->[3], which can be simplified to $a->[2][3], and so on. > > Also, if called_sub modifies that array that was passed in by reference, > does it stay changed outside the subroutine? Or do I have to return > something from the subroutine and capture it on the outside? If you pass an array by reference, there is no copy in the subroutine. Any changes you make to the array in the subroutine will be retained in the calling program after the subroutine returns. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/