Why not just send the code straight to "perl -cw" itself?
sub test_code {
my $code_to_check = shift;
my $pid = open(PERL, "|-");
if (!$pid) {
die "fork: $!" unless defined $pid;
exec("/usr/bin/perl", "-cw") or die "/usr/bin/perl: $!";
}
print PERL $code_to_check;
close(PERL);
return !$?; # $? == 0 means compile succeeded
}
You may want to close STDIN/STDERR to handle any output the forked Perl process gives, and just rely on the exit status, or use
open2/
open3 if you want to capture the compilation messages Perl gives you.