On 9/4/07, James <[EMAIL PROTECTED]> wrote:

> My issue is that I can get the sub working fine, iterating though the 2d array
> correctly until I put a return statement in.  Once I put the return statement
> in, the sub only reads one slice of the 2d array, thus not returning a
> correctly updated array... why???

When perl executes the return statement, the subroutine returns
immediately. If you have completed only one iteration of the loop by
the time the return statement comes up, your sub won't process any
more of the array.

Perhaps you come to Perl from another programming language background.
In some programming languages, subroutines don't return early and
loops don't end early, at least under normal circumstances. Perl is
the other kind of language.

If, where you have a return statement, you instead merely wish to
store away the return value and continue to the "natural" end of the
subroutine, the common way to code that is with a variable to hold the
return data, something like this:

  sub frobnicate {
    my $return_value;
    foreach (1..10) {
      ...
      if ($wilma > 0) {
        # Store away the return data
        $return_value = $fred * $_ + $^T;
      }
    }
    # the foreach loop runs to the end
    ...
    return $return_value;
  }

It's perhaps even more common to use an array or hash variable to hold
the return data, depending upon the nature of the return value and
choice of algorithm. I'm not sure which one would be a good choice for
what you're doing, though.

Does this clear up your mystery? Hope this helps!

--Tom Phoenix
Stonehenge Perl Training

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to