in reply to Sharing a variable between subroutines

If i need for a variable to be 'shared' by other subroutines, then i just pass that variable along as an argument to those subroutines. If you are simply passing a reference to an array, then you are not passing the entire array.

I rewrote your code with some adjustments:

use strict; &specific(); sub callme { my ($array,$i) = @_; $array->[$i] = "printme-"; # note the arrow operator } sub specific { my $array = [(0..5)]; &callme($array,$_) for (0..$#$array); print join("\n", @$array), "\n"; }
The first thing to notice is that $array is a reference:
# this is not really correct: my @array = [0,1,2,3,4,5]; # use this: my $array = [(0,1,2,3,4,5)]; # or this: my @array = (0,1,2,3,4,5);
Also, using subroutine prototypes is not recommended. Last note, why iterate through an array one element at a time and pass the index and the array off to another subroutine? Wouldn't simply passing the array reference to a sub that iterates it be better?

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
F--F--F--F--F--F--F--F--
(the triplet paradiddle)

Replies are listed 'Best First'.
Re: (jeffa) Re: Sharing a variable between subroutines
by Anonymous Monk on Dec 28, 2001 at 21:47 UTC
    Aah, I totally forgot about that pointer-stuff (the arrow-operator)...
    I think I'll give this a try. The iteration in the outer sub was just an example.
    I have a two-dimensional array, the y-coordinate ("lines") is determined in the "outer" subroutine and the x-coordinate ("columns") is worked on in the called "inner" subroutine.
    This makes the code more readable IMO.

    Thanks to everyone who bothered to help me and have a happy new y2k2 all!
    Micha