简体   繁体   中英

How to eval memory group in a variable using perl?

In a perl script, I want to evaluate memory group special variable in a string variable :

my $string="3-4";
my $cal='first is $1;second is $2';
my $regex='^(.)-(.)$';

if($string=~ $regex){
    print $cal;
        #print "first is $1;second is $2";
}

I want to print : "first is 3;second is 4" (like in second print).

In my sample, there is only 2 special variable but the number of special char cannot be determined in advance because $cal and $regex are stored in a database.

How can I evaluate the string $cal (like with eval in php ) ?

Sounds like you want to define a pattern into which your matches will be inserted? You could use printf for that, eg

my $string="3-4";
my $cal="%s %s\n";
if($string=~ '^(.)-(.)$'){
    printf($cal, $1, $2);
}

If you simply want to join all matches together, and you don't know how many there might be, try something like this

my @matches=$string=~ '^(.)-(.)$';
if (scalar(@matches))
{
    print join(' ',@matches);
}
print eval "\"$cal\"","\n";

The outer dblquotes are for eval "", the inner escaped quotes are for interpolation inside print "$1 $2","\\n";

or, you can combine the print segments like this print eval "\\"$cal\\n\\"";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM