[lug] Perl - How to pass by Reference?
Siegfried Heintze
siegfried at heintze.com
Wed Mar 1 16:56:51 MST 2006
This is a great exercise that is not covered well in any of the tutorials I
read when I was trying to learn perl. I found this lesson very painful.
First: Why are you trying to pass by reference?
There are easier alternatives like returning a list as the function value.
The list would contain the changed values.
You can pass a scalar by reference. Are you a C programmer? There are some
analogs if you are.
To pass a scalar by reference you insert the "\" in front of the function
argument in the main program. C programmers are accustomed to using a "&"
but that has different meanings in perl.
To receive a scalar by reference inside the function implementation, you use
an additional "$". So everywhere you have "$val" you would put "$$val". C
programmers would put an extra "*" in front but that also has a different
meaning in Perl.
Actually all arguments are passed by reference in perl. The reason your
program is not working is that you made a copy of the original when you
typed "my $val = pop @_". With the changes above, you will be making a copy
of the reference, and not the original. So an alternative would be to say
"$[0] = 'goodbye'; '. Nice transparent code, huh?
Beware: things get more complex when passing arrays as function arguments.
Siegfried
-----Original Message-----
From: lug-bounces at lug.boulder.co.us [mailto:lug-bounces at lug.boulder.co.us]
On Behalf Of Bill Thoen
Sent: Wednesday, March 01, 2006 3:37 PM
To: lug at lug.boulder.co.us
Subject: [lug] Perl - How to pass by Reference?
In this contrived example, I want to pass $test by reference so the
changeit() subroutine can change it, but I can't figure out how to do this
with 'strict' and 'warnings' turned on. Can anyone here tell me what I need
to do to fix this? (as you can tell, I'm trying to learn Perl)
#!/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;
}
}
_______________________________________________
Web Page: http://lug.boulder.co.us
Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
Join us on IRC: lug.boulder.co.us port=6667 channel=#colug
More information about the LUG
mailing list