Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to do the following:
#!/usr/misc/bin/perl5 -w use strict; my $blahblah = 5; my $ref_to_blahblah = \$blahblah; print "$$ref_to_blahblah\n"; fubar($ref_to_blahblah); print "$$ref_to_blahblah\n"; sub fubar { $$_[0] = 4; print "$$_[0]\n"; }
Right now, the output is:
5
4
5
I want to have fubar() change $blahblah, so that the ouput is 5-4-4. I've looked around and I can't find a way to do this. Help!

Replies are listed 'Best First'.
Re: Passing pointers around
by extremely (Priest) on Jan 15, 2001 at 02:37 UTC
    Change fubar() to this:
    sub fubar { ${$_[0]} = 4; print "${$_[0]}\n"; }

    Unfortunately for you, this is one of those cases where Perl's Do-What-I-Mean nature happens to do what someone else meant. In effect, what you did was set ${$_}[0] = 4; which, since $_ isn't declared but is special winds up creating an anonymous array in $_ which has a single item in it, 4. All that without complaining since $_ has so much magic surrounding it. =)

    The problem there is that perl binds "$" stronger than "[]" so it deref's $_ rather than deref'ing @_'s first item. HTH, BTW this sort of question really belongs in Seekers of Perl Wisdom...

Re: Passing pointers around
by a (Friar) on Jan 15, 2001 at 11:24 UTC
    This seems to work:
    sub fubar { my $ref = shift; ${$ref} = 4; print "$$ref\n"; }
    and I'm assuming you're using ref's to scalars as a learning experience. I dunno if the $$_&lbr;0] (sorry, forgot the code for left bracket) is putting another layer of ref in there. Likewise:
    feebar(\$blahblah); sub feebar { my $ref = shift; $$ref = 4; print "$$ref\n"; }
    works too. More questions? Buy Object Oriented Perl (by D. Conway) As good a 30 bucks as you can spend on perl manuals (not the best, but as good as ... ;-).

    a

Re: Passing pointers around
by repson (Chaplain) on Jan 15, 2001 at 07:03 UTC
    How about
    my $blahblah = 5; print "$blahblah\n"; fubar($blahblah); print "$blahblah\n"; sub fubar { $_[0] = 4; print "$_[0]\n"; }