[lug] Perl - How to pass by Reference?

Zan Lynx zlynx at acm.org
Wed Mar 1 18:14:31 MST 2006


On Wed, 2006-03-01 at 17:27 -0700, Bill Thoen wrote:
> On Wed, Mar 01, 2006 at 04:56:51PM -0700, Siegfried Heintze wrote:
> > 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.
> 
> Yes... I'm afraid I'm trying to do something in a non-Perl way. I'm having
> even more trouble with the Perl book I'm using. It must be way out of date
> because it doesn't even mention things like my(), much less give me
> anything useful about referencing/dereferencing passed parameters. 

You really must get an updated book, if you're trying to learn Perl from
the book.  It sounds like you have a book for version 4 instead of
version 5 Perl.  Things changed a lot.

> > First: Why are you trying to pass by reference? 
> 
> So I can have the subroutine return a boolean value while also being able
> to change more than one parameter as well.

The more programming that I do, the more I dislike functions that modify
their arguments.

You could just return a list to the caller.  

Like:
sub f
{
	my ($a, $b) = @_;
	$b = Stuff($b);
	return ($a eq 'FOO', $b);
}

And then:

($c, $d) = f(1, 2);

And of course a favorite trick is that you can return a list or a scalar
depending on what the caller asked for:

sub f
{
	my ($a, $b) = @_;
	$b = Stuff($b);
	return wantarray ? split(/:/, $b) : $b;
}
-- 
Zan Lynx <zlynx at acm.org>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 191 bytes
Desc: This is a digitally signed message part
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20060301/aea28df1/attachment.pgp>


More information about the LUG mailing list