On Fri, Oct 15, 2010 at 11:40 PM, Owen Chavez
<owen.chavez314...@gmail.com> wrote:
> I've started experimenting with the use of subroutines in place of large,
> repeating blocks of code in a few of my programs.  Without exception, these
> subroutines require variables defined outside of the subroutine.  Unless I'm
> mistaken, the only way to make these variables available within the
> subroutine is to define them as global variables using "our."

You, good sir, are mistaken. :) Globals are very rarely /required/.
Subroutines accept arguments for a reason. Not only does it make them
reusable for different sources of data, but it also restricts their
influence over the program. Global variables are accessible by the
entire program. Even file scope[1] variables are accessible by an
entire file! That means that you have a lot more chances to make a
mistake that causes a bug that makes the code do the wrong thing. `my`
is your friend in this regard.

Basically no matter which programming language you are using you
typically want to avoid global scope whenever you can. Take an hour
out of your life to watch the following video (even if you don't
understand it right away):

http://www.youtube.com/watch?v=-FRm3VPhseI

It's somewhat Java-centric, but it applies to basically all
programming languages. The more code that is allowed to access a given
piece of data the more likely that the program is to incorrectly
manipulate that data. The code is written by people and people are
fallible.

In Perl, arguments can be passed to your own custom subroutines the
same way that they are passed to built-in subroutines. As
comma-separated lists, "optionally" enclosed in parenthesis. For
example:

#!/usr/bin/env perl

use strict;
use warnings;

# Passes "foo", "bar", "baz", and "\n" to print.
print "foo", "bar", "baz", "\n";

# Same as above.
print("foo", "bar", "baz", "\n");

sub print_sum
{
    my ($a, $b) = @_;

    print($a + $b, "\n");
}

# Passes 5 and 10 to print_sum.
print_sum 5, 10;

# Same as above.
print_sum(5, 10);

my $lhs = 5;
my $rhs = 10;

# Passes the values of $lhs and $rhs to print_sum.
# Effectively, the same as above.
print_sum($lhs, $rhs);

__END__

Argument passing allows you to limit /scope/, which is very important
for reliable coding. It can be acceptable to use global variables for
simple scripts, but if you're writing non-trivial programs then you
should probably avoid global /state/ and try to limit scope as much as
possible.

[1] http://en.wikipedia.org/wiki/Scope_(programming)

-- 
Brandon McCaig <bamcc...@gmail.com>
V zrna gur orfg jvgu jung V fnl. Vg qbrfa'g nyjnlf fbhaq gung jnl.
Castopulence Software <http://www.castopulence.org/> <bamcc...@castopulence.org>

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to