International English version Traditional Chinese version
Domain Registration with Web HostingWeb site Hosting with Various supportRegistrar Transfer with Web Hosting

Passing by reference in PERL

Sometimes you don't want to pass the value of an array to a subroutine but rather the name of it, so that the subroutine can modify the global copy of it rather than working with a local copy. In perl you can refer to all the objects of a particular name by prefixing the name with a star: *foo. When evaluated, it produces a scalar value that represents all the objects of that name, including any filehandle, format or subroutine. When assigned to within a local() operation, it causes the name mentioned to refer to whatever * value was assigned to it. For example:

   sub doubleary {
      local(*someary) = @_;
      foreach $elem (@someary) {
         $elem *= 2;
      }
   }
   do doubleary(*foo);
   do doubleary(*bar);
Assignment to *name is currently recommended only inside a local(). You can actually assign to *name anywhere, but the previous referent of *name may be stranded forever. This may or may not bother you.

Note that scalars are already passed by reference, so you can modify scalar arguments without using this mechanism by referring explicitly to the $_[nnn] in question. You can modify all the elements of an array by passing all the elements as scalars, but you have to use the * mechanism to push, pop or change the size of an array. The * mechanism will probably be more efficient in any case.

Since a *name value contains unprintable binary data, if it is used as an argument in a print, or as a %s argument in a printf or sprintf, it then has the value '*name', just so it prints out pretty.

Even if you don't want to modify an array, this mechanism is useful for passing multiple arrays in a single LIST, since normally the LIST mechanism will merge all the array values so that you can't extract out the individual arrays.

Click here to go back to the Perl index

Home | Support | Check | Host | Transfer | Whois | More Technology Services

© 1996-2008 Wyith Ltd dba DomainAvenue.com. All rights reserved.

Canada | USA | UK | Belgium | Italy | Hongkong | Singapore