You are on page 1of 1

Strict subs

During the course of this series, I've deliberately avoided mentioning all sorts of tricks that allow you to write more compact Perl. This is because of a simple rule: readability always wins. Not only can compactness make it difficult to read code, it can sometimes have weird side effects! The way Perl looks up subs in your program is an example. Take a look at this pair of three-line programs:
$a = test_value; print "First program: ", $a, "\n"; sub test_value { return "test passed"; } sub test_value { return "test passed"; } $a = test_value; print "Second program: ", $a, "\n";

The same program with one little, insignificant line moved, right? In both cases we have a test_value() sub and we want to put its result into $a. And yet, when we run the two programs, we get two different results:
First program's result: test_value Second program's result: test passed

The reason why we get two different results is a little convoluted. In the first program, at the point we get to $a = test_value;, Perl doesn't know of any test_value() sub, because it hasn't gotten that far yet. This means that test_value is interpreted as if it were the string 'test_value'. In the second program, the definition of test_value() comes before the $a = test_value; line. Since Perl has a test_value() sub to call, that's what it thinks test_value means. The technical term for isolated words like test_value that might be subs and might be strings depending on context, by the way, is bareword. Perl's handling of barewords can be confusing, and it can cause two different types of bug.

You might also like