Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using data passed by reference to a subroutine

Status
Not open for further replies.

wardy66

Programmer
Jun 18, 2002
102
AU
Hello - me again....

Take this example code:
Code:
my @array = (1, 2, 3);
pass_array( \@array );

sub pass_array ($) {
my $aref = shift;
$$aref[1]++
}

This should work and add one to element [1] in the array @array.

My question is, how can I write my subs more legibly by being able to do something like
Code:
$sub_array[1]++
and get the same result?

Is it something to do with typeglobs?

Some of my subroutines working on passed references are getting pretty ugly with @{ and $$ all over the place!

TIA
 
I would say $aref->[1]++, using the "->" as the dereferencing operator. You may or may not consider
that more legible. I've never used "$$var". I think I read
in the Camel book that "$$var" is not recommended, though I don't recall why. Knowing that it wasn't recommended was
enough to make me leave it alone -- and I like the arrows.
 
Thanks, mikevh

I have been using the $$ and the -> depending on what looks nicest :)

Still, I would rather just use $array[1] in my subroutines but I can't work out how to make it refer to the same data.
 
You are correct that you can do this with typeglobs. You can't 'use strict' though. it doesn't allow for this type of "advanced" referencing. To accomplish this change your posted code to look something like

@array = (1, 2, 3);
&pass_array( \*array );

sub pass_array ($) {
*aref = shift;
$aref[1]++
}

if you are going to use subroutine prototypes then you need to put the subroutine definition before it's called or use the '&mysubroutine' syntax. otherwise Perl can't check the prototype (it will complain about this if warnings are enabled).

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top