Clean-Eval
view release on metacpan or search on metacpan
lib/Clean/Eval.pm view on Meta::CPAN
modules, or otherwise doing things with no meaningful scalar result. If
you need a value back from a string eval, write to an C<our> package
variable from inside the string, or wrap a real C<eval $str> inside a
C<clean_eval> block and capture from there.
=head2 C<clean_string_eval> does not see the caller's lexicals
With a raw C<eval $string>, the eval'd code can see any C<my> variables
in the surrounding scope. C<clean_string_eval> cannot: the string is
eval'd inside this module, so the caller's lexicals are out of reach.
Only package globals are visible.
use Clean::Eval qw/clean_string_eval/;
my $x = 42;
my $ret = clean_string_eval 'print $x';
# $ret is an error: "Global symbol $x requires explicit package name"
# (or, without strict, $x is just an unrelated undef global)
our $y = 42;
clean_string_eval 'print $y'; # prints 42 - $y is a package global
If you need to feed values in, pass them through globals you control or
through the environment, or build a closure and use C<clean_eval> with a
block instead.
=head2 C<return> inside the block returns from the block, not the caller
The block passed to C<clean_eval> is an anonymous subroutine. A C<return>
inside it returns from that anonymous subroutine - not from the
enclosing named sub - and C<clean_eval> still gets control back and
returns C<1> for success.
sub do_work {
my $ok = clean_eval {
return if $skip; # returns from the block only
risky_thing();
};
return 0 unless $ok;
...
}
This matches the behavior of plain C<eval { ... }>.
=head2 Cannot pass a coderef variable with block syntax
The C<(&)> prototype makes C<clean_eval> parse a literal block; it will
not accept a coderef in scalar variable form:
my $cref = sub { die "foo" };
clean_eval $cref; # syntax error / wrong parse
Workarounds:
clean_eval(\&named_sub); # named sub via \&
clean_eval { $cref->() }; # wrap in a literal block
&Clean::Eval::clean_eval($cref); # bypass the prototype
=head1 SEE ALSO
L<Try::Tiny>, L<Syntax::Keyword::Try>, L<Feature::Compat::Try>.
=head1 SOURCE
The source code repository for Clean-Eval can be found at
F<https://github.com/exodist/Clean-Eval/>.
=head1 MAINTAINERS
=over 4
=item Chad Granum E<lt>exodist@cpan.orgE<gt>
=back
=head1 AUTHORS
=over 4
=item Chad Granum E<lt>exodist@cpan.orgE<gt>
=back
=head1 COPYRIGHT
Copyright 2026 Chad Granum E<lt>exodist7@gmail.comE<gt>.
This program is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
See F<http://dev.perl.org/licenses/>
=cut
( run in 1.399 second using v1.01-cache-2.11-cpan-6de40a662fe )