in reply to Re: Simple Pass By Reference
in thread Simple Pass By Reference

I would really drop the our and typeglob usage here. I feel like it's "overkill" for what [id://tomazos] is trying to do.

The following is also an interesting solution, that is quite similar to [id://friedo]'s one, but uses prototype to move referencing backslash from main script into the function code.

#!/usr/bin/perl use strict; use warnings; sub modify (\$) { my $string_ref = $_[0]; $$string_ref =~ s/a/x/g; } my $string = 'abc'; print "before `$string'\n"; # abc modify $string; print "after `$string'\n"; # xbc

Anyway, probably it is best to leave the \ char inside the main script. In this way, it is immediately clear that you're passing a reference, and not the real scalar. In the latter case, you could be tempted to think that a return value is also expected from the modify() function, which actually is not.

Replies are listed 'Best First'.
Re^3: Simple Pass By Reference
by tomazos (Deacon) on Jul 26, 2005 at 17:27 UTC
    Sure, that's using referencing/dereferencing - which is fine, but I'd rather have a normal scalar name ($string rather than $$string_ref).

    In this example its trivial, but if you have a lot of variables around, its hard to keep track of whats a reference and whats not.

    -Andrew.


    Andrew Tomazos  |  andrew@tomazos.com  |  www.tomazos.com