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

Hi perl scripters! I have a problem. I have some arrays in file config.pl with names @a,@b,@c etc. I want to use their lenght from another file in loop like change only name of the arrays. Script works if I put in expression the name of array: for ($br=0; $br<=$#config::a; $br++) {} How to pass on the name of array like parameter in above expression?

Replies are listed 'Best First'.
Re: Pass on name of array
by tadman (Prior) on Apr 05, 2001 at 19:28 UTC
    You can make a sub accept an array and you can act on it without knowing the 'name' of the array you are receiving. This is done with references:
    sub DoSomethingToArray (\@) { my ($array) = @_; for ($br = 0; $br <= $#{$array}; $br++) { # Do stuff with @$array using references } } # Call it simply as: DoSomethingToArray(@config::a); DoSomethingToArray(@config::b); DoSomethingToArray(@config::c);
    Note that this function has a prototype which tells Perl that you don't want the array (@), but a reference to it. Without this prototype, the contents of the array are passed to the function, which is of less use.

    Update: Changed '<' comparison to '<=' in the for loop as per ton's correction below.
      Quick note: if you use the above solution, change the '<' in the conditional of the for loop to '<='. e.g.:
      for ($br = 0; $br <= $#{$array}; $br++)
      '#' when applied to arrays returns the last valid index, so a less than conditional will fail on the last valid index, meaning that index will never be used. Alternately, you could use the size of the array:
      for ($br = 0; $br <= @$array; $br++)
      or, to eliminate any ambiguity,
      for ($br = 0; $br <= scalar(@$array); $br++)
        for ($br = 0; $br <= scalar(@$array); $br++)
        Please don't add the extra scalar. It confuses your maintainer, unless you comment it as
        # we don't need scalar here... it's for the dummies who can't grok sca +lar context yet
        So I would fail it out of a code review without that comment.

        If someone doesn't understand that <= provides scalar context, they have no business editing my code.

        -- Randal L. Schwartz, Perl hacker