Here is some fairly verbose, plain-vanilla code
that illustrates
some of the points made in the posts above. The general
recommendation being that you avoid using
variables floating around in
global space. Rather, feed the values
you need explicitly to and from the subroutine.
This discipline will help you a lot
as your programs get larger and
more complex.
#!/usr/bin/perl5 -w
use strict;
my ($is_okay, $value);
sub return_okay {
my $test_string = shift;
my $private_result = ($test_string =~ /myregex/);
return ($private_result);
}
sub return_okay2 { # concise version
return ($_[0] =~ /myregex/);
}
sub modify_okay { # but see WARNING below
# Called as: modify_okay($string, $result_flag)
$_[1] = ($_[0] =~ /myregex/);
}
my @vals = qw(abcdefg myregex tuvwxyz);
print "Using a return value:\n";
foreach $value (@vals) {
$is_okay = return_okay2($value); ###
if ($is_okay) {
print "$value is okay.\n";
}
else {
print "$value is not okay.\n";
}
}
print "\nUsing a modified value:\n";
foreach $value (@vals) {
modify_okay($value, $is_okay); ###
if ($is_okay) {
print "$value is okay.\n";
}
else {
print "$value is not okay.\n";
}
}
# WARNING: the modify method can blow up on you
# Notice that the following line causes a fatal error
# because of the attempt to modify a constant:
modify_okay("some string", 1);
print "And this never prints\n";
Is there a chance you will forget at some point and
pass the modify version a constant? We've all done it.
So will you.
Use return values. They don't choke trying to modify
constants and (bonus) they are more clear. You have to
look twice at the call to modify_okay() to figure out
that the first variable is input but the second variable
is being modified behind your back.
P.S. The above was intentionally verbose. With a
little jiggering, the foreach loops can be condensed to:
for (@vals) {
my $qualifier = return_okay2($_) ? "" : " not";
print "$_ is$qualifier okay.\n";
}
or...
print map "$_ is ".(return_okay2($_)?'':' not')." okay\n", @vals;
Which really doesn't relate to your question, but is fun
anyway! |