Who needs string eval?

nicholas on 2006-04-14T22:39:12

use strict;
use warnings;
require PerlIO::scalar;

unshift @INC, sub {
    my $file = $_[1];
    if (ref $file) {
        my $fh;
        open $fh, "<", $file or die $!;
        return $fh;
    }
};

do \('print "Hello ' . (shift || "world") . '\n"');

No string eval there. No sir. I wonder if it circumvents things like Safe...

Update:

This is terser. You don't need the BEGIN block, but it demonstrates that the technique is robust and automatically lets regular filenames through. (In this case PerlIO/scalar.pm)

use strict;
use warnings;

BEGIN {
    unshift @INC, sub {
        $_[1];
    };
}

require PerlIO::scalar;

open my $fh, "<", \('print "Hello ' . (shift || "world") . '\n"');
do $fh;