<p>I need to add unit testing to some old scripts, the scripts are all basically in the following form:</p>

<pre><code>#!/usr/bin/perl

# Main code
foo();
bar();

# subs
sub foo {

}
sub bar {

}
</code></pre>

<p>If I try to 'require' this code in a unit test, the main section of the code will run, where as I want to be able to just test "foo" in isolation.</p>

<p>Is there any way to do this without moving foo,bar into a seperate .pm file?</p>

Assuming you have no security concerns, wrap it in a sub { ... } and eval it:
```
```
use File::Slurp "read_file";
eval "package Script; sub {" . read_file("script") . "}";

is(Script::foo(), "foo");
```
```
(taking care that the eval isn't in scope of any lexicals that would be closed over by the script).