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

i am trying to change the content of an array from with in a subroutine , i am passing the array as a ref to the subroutine but its not working. MY Code::
my @array=(one,two,three); my $arref=\@array; sub func ($aref) >> sub definition { $aref->[0]="four"; } &func($arref); >>calling the sub print "@array";
O/p : its is still coming as --> one two three i am expecting o/p as -> four two three ...please help me where is it going wrong

Replies are listed 'Best First'.
Re: array ref problem
by almut (Canon) on Nov 03, 2008 at 07:31 UTC

    Always use strict; use warnings;. You'd have gotten several warnings that would have indicated that subroutine parameters are not specified that way in Perl.   Try this:

    use strict; use warnings; my @array=qw(one two three); my $arref=\@array; sub func { my $aref = shift; $aref->[0]="four"; } &func($arref); print "@array";
Re: array ref problem
by chrism01 (Friar) on Nov 03, 2008 at 07:35 UTC
    Also, you don't call a sub with '&', just name it. That's old-school Perl4, now deprecated. In fact the only time you would now (afaik) is if you want a a ref-to-sub.
      In fact the only time you would now (afaik) is if you want a a ref-to-sub.

      or when forwarding to another sub:

      sub _foo_impl { ... } sub foo { .... &_foo_impl; ... } foo(1,2,3); # _foo_impl(1,2,3) gets called

      -- 
      Ronald Fischer <ynnor@mm.st>
        In fact the only time you would now (afaik) is if you want a a ref-to-sub.
        or when forwarding to another sub:

        ...or when you want to bypass the prototype of the sub you're calling.