in reply to Re^3: Passing an array to a subroutine help?!
in thread Passing an array to a subroutine help?!

We were taught in class to call subroutines by the method I have shown above which is commented out.

That's a shame; your instructor is doing you and your colleagues a disservice. That syntax has unfortunate side effects.

$arraysize isn't a global variable in the program because I used my $arraysize, right?

$arraysize is a lexical variable due to your use of my, but it is visible to the whole program because its lexical scope is the file itself. It's effectively global, even though it's not a package variable.

Shouldn't they just work in the print statements after they're returned from the subroutines?

The values returned from the functions (I use these words very carefully) come from lexical variables with smaller scopes—the scope of the functions themselves:

my $max = maximum(@values); sub maximum { my $max = shift; for my $arg (@_) { $max = $arg if $arg > $max; } return $max; }

There are two lexical variables named $max in this code. Within the function, all references to $max refer to the innermost variable. If it didn't declare $max as a lexical within the function, all references to $max would refer to the outer (file-scoped) $max. You're correct that you wouldn't have to use return explicitly in that case...

... but when you do treat your functions as black boxes which take inputs and return results and do not modify external variables, you tend to end up with better code. You can be certain that your functions do not modify any external variables on which other functions rely, which makes it much easier to write larger and more robust programs.

If you'd like to learn more details about lexical scoping and functions and ways to write reliable Perl 5 code, my book Modern Perl is available in several electronic versions for free. It might be a good supplement for your class.