[lug] Perl - How to pass by Reference?

Ted Logan ted.logan at gmail.com
Wed Mar 1 15:57:41 MST 2006


On 3/1/06, Bill Thoen <bthoen at gisnet.com> wrote:
> In this contrived example, I want to pass $test by reference so the
> changeit() subroutine can change it

Use \$var to create a reference to a scalar, and $$var to dereference
the reference. So your example becomes:

#!/usr/bin/perl

use strict;
use warnings;

&main();

sub main {
 my $test='Hello';

 if (&changeit (\$test)) {
   print "$test\n";
 }
 else {
   print "failed\n";
 }
}

sub changeit {
 my $val = pop @_;

 if ($$val eq 'Hello') {
   $$val = 'Goodbye';
   return 1;
 }
 else {
   return 0;
 }
}

--
Ted Logan
Finally-employed Engineer
ted.logan at gmail.com
http://jaeger.festing.org/



More information about the LUG mailing list