in reply to Pass on name of array

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.

Replies are listed 'Best First'.
Re: Re: Pass on name of array
by ton (Friar) on Apr 05, 2001 at 21:49 UTC
    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

        I think that is too harsh. I often put scalar in when it is not neededfor the same reason that I use parens which are not needed - I know that the code is likely to be edited by someone who has not memorized the various contexts.

        Now in a perfect all Perl world, I would agree with you. But when my code needs to be understood by programmers who are not primarily Perl programmers, well I am confident that I can teach them to remember that Perl has both scalar and list contexts, and they do different things. But when they have to edit my Perl after a month in other languages, I do not believe that they will retain fast reactions for which syntactic constructs imply scalar context.

        So I leave in the crutch, and since everyone knows that I do this deliberately, I don't see any reason to comment it.

        OTOH in code which will only be seen by people who are supposed to be competent Perl programmers, well I drop it...