in reply to Simple Pass By Reference

Try this.

  • It uses a prototype to save you from explicitly taking a reference when you call the sub.
  • It assigns the reference to a localised glob to avoid the need for explicit dereferencing inside the sub.
  • It uses our to satisfy strict.

    Result: Efficient pass-by-reference without the pain of dereferencing.

    #! perl -slw use strict; sub modify (\$) { our $data; local *data = $_[ 0 ]; $data =~ s[this][that]g; return; } my $string = 'this & that;' x 10000; modify $string; print substr $string, 0, 24;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
  • Replies are listed 'Best First'.
    Re^2: Simple Pass By Reference
    by cosimo (Hermit) on Jul 26, 2005 at 16:01 UTC

      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.

        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