Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want write dynamic perl code inside my perl program.

Example :

1) Assign perl block to string

$szBlock = q( sub { if ( $x > $y ) { return "X greater \n" ; } else { return "y greater \n" ; } } ) ;
2) I want Assign values of $x and $y
$x=100 ; $y= 200 ;
3) Then i want execute $szBlock in side perl program.

In my app depends on paramter i want execute dynamic perl block in my program.

email : gback@drugstore.com

Edit, BazB: added formatting.

Replies are listed 'Best First'.
Re: dynamic perl code inside my perl program
by davido (Cardinal) on Oct 20, 2003 at 18:38 UTC
    For dynamic code you want eval. That's one of its most common duties.

    However, your example doesn't really demonstrate a real need for dynamic code. If all you want is a function that returns one thing, or another depending on the outcome of a comparison, you can just use simple program logic with if statements or the ?: trinary operator.

    You may even consider double-barreled-closures as a means of returning a subref to one of several subs depending on the outcome of the logic test.

    But eval is always a sure bet for dynamic code.


    Dave


    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein
Re: dynamic perl code inside my perl program
by Limbic~Region (Chancellor) on Oct 20, 2003 at 18:53 UTC
    Anonymous Monk,
    In this case, you can get away without using eval.
    #!/usr/bin/perl -w use strict; my ($x, $y) = (100, 200); my $dynamic = sub { return "X is bigger" if $x > $y; return "Y is bigger" if $x < $y; }; print $dynamic->(), "\n"; $x = 500; print $dynamic->(), "\n";
    Cheers - L~R
Re: dynamic perl code inside my perl program
by flounder99 (Friar) on Oct 20, 2003 at 19:49 UTC
    Remember that if you eval $szBlock it will return a reference to the subroutine. You will then have to call that subroutine reference.

    This looks like homework so I shouldn't be giving you the answer but I don't know of any better way to explain it.

    use strict; my $szBlock = q( sub { if ( $x > $y ) { return "X greater \n" ; } else { return "y greater \n" ; } } ) ; # # $szBlock is a string containing the text of the subroutine. # my ($x, $y) = (100,200); # # Set up $x and $y (you will have to do this before the eval # or strict won't like it.) # my $subref = eval $szBlock; # # if the eval worked $subref now has a reference to the # compiled subroutine # die $@ if $@; # # $@ will be true if the eval failed (if there was a typo in $szBlock) # # # Now we call the subroutine by "dereferencing" the reference in $subr +ef # print &$subref;
    This will print
    y greater

    --

    flounder