Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: Creating subroutines on the fly

by saskaqueer (Friar)
on Feb 17, 2005 at 07:55 UTC ( [id://431856]=note: print w/replies, xml ) Need Help??


in reply to Creating subroutines on the fly

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->(); }

Replies are listed 'Best First'.
Re^2: Creating subroutines on the fly
by TedYoung (Deacon) on Feb 17, 2005 at 14:17 UTC

    Putting the eval inside a sub can be must slower if that sub is called many times (more than once) since Perl will have to recompile $code each time the sub is called.

    my $sub = eval "sub { $code }"; compiles the Perl code once, regardless of how many times you execute it.

    Ted Young

    ($$<<$$=>$$<=>$$<=$$>>$$) always returns 1. :-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://431856]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2024-04-23 09:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found