Everybody else seems to be providing my $sub = eval "sub { $code }";. I've never used this method; heck, I've never even thought of doing it that way. It just seems unnatural to me to have it strung along in that manner. I do it the other way around: my $sub = sub { eval $code };. Besides, doing it this way allows for simpler error handling.
#!/usr/bin/perl -w use strict; my $code = q{ open( my $fh, '<', 'foo.txt' ) or die("open failed: $!") + }; my $sub = sub { eval($code) or die("error in eval(): $@"); }; $sub->();
The obvious downside is that this will only work for anonymous subs, and not named ones. The only way I can think of doing anything near 'named subs' is to abuse references, which is ugly:
#!/usr/bin/perl -w use strict; my $code = q{ open( my $fh, '<', 'foo.txt' ) or die("open failed: $!") + }; my $sub = sub { eval($code) or die("error in eval(): $@"); }; my $sub_name = 'do_this'; { no warnings 'once'; no strict qw(refs vars); $$sub_name = $sub; $do_this->(); }
In reply to Re: Creating subroutines on the fly
by saskaqueer
in thread Creating subroutines on the fly
by pander
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |