Then what you're after, as I mentioned, is the string version of eval:
my $data = 'Just another Perl hacker,';
my $expression = 's/(another)/a/';
my $match_var;
my $result = eval <<"END_EVAL";
my \$success = \$data =~ $expression;
\$match_var = \$success ? \$1 : undef;
\$success;
END_EVAL
if( $result ) {
print "$match_var => $data\n";
}
It would be better if instead of passing "$match_var out of the eval's scope you instead passed a reference to a copy of @- and @+; that way you could look at scalar @- to determine how many captures were produced, and then use substr on an original copy of the string to determine what those captures actually were. And while you're at it, you might also need to deal with named captures.
But this opens your code to some serious problems. Consider the following:
my $data = 'Just another Perl hacker,';
my $expression = 's/(another)/a/; print "Hello world!\n";';
my $match_var;
my $result = eval <<"END_EVAL";
my \$success = \$data =~ $expression;
\$match_var = \$success ? \$1 : undef;
\$success;
END_EVAL
if( $result ) {
print "$match_var => $data\n";
}
Now by supplying a semicolon in the appropriate place within the code string, the user was able to move on, executing arbitrary additional code (in this case, print "Hello world!\n";). That's possibly innocuous, but how about 'while ( my( $key, $value ) = each %ENV ) { ... }', or how about backticks or a system call, or even unlink?
Maybe you can trust your users. But I wouldn't even trust myself with code that exposes that sort of security flaw. No.....you're much better off staying away from the temptation to take the easy solution. It might save you an hour of coding now, but imagine how time consuming it will be when a user does something malicious because he felt snubbed by how you failed to notice him in the break room.
The safest approach is to find a way to allow users to choose between different operations that you explicitly expose. Much less safe but still better than simple eval would be to use the Safe module's reval method. That will protect you against many malicious attacks, but won't protect from denial of service attacks. A user could still tie up a process forever and consume as much memory as you have available.
|