Variable interpolation in Variables possible?

K

kw

Hello Group,

i would like to do in perl something similar to the eval command in a
korn shell.

First i define some scalar variables $a and $b
my $a="123";
my $b="abc";

then i define a scalar $c to be the composition of $a and $b

my $c='$a $b';

then many line of code later and probably changes of $a and $b i want
to use $c for instance so as to print it:

print $c;

I know there ist no variable interpolation after $c has been
substituted but how can i make this happen?

In the shell i would write

eval print $c
 
P

Paul Lalli

kw said:
i would like to do in perl something similar to the eval command in a
korn shell.

You have asked a Self Answering Question

perldoc -f eval
First i define some scalar variables $a and $b
my $a="123";
my $b="abc";

then i define a scalar $c to be the composition of $a and $b

my $c='$a $b';

That's simply the value of $a, a space, and the value of $b. If you
were to evaluate this, you would likely get a syntax error. I think
you probably want to concatenate the two values:
my $c = '$a . $b';
#(or possibly concatenate them with a space in between)
my $c = '$a . " " . $b';
#or
my $c = '"$a $b"';
then many line of code later and probably changes of $a and $b i want
to use $c for instance so as to print it:

print $c;

I know there ist no variable interpolation after $c has been
substituted but how can i make this happen?

In the shell i would write

eval print $c

In perl, you want to evaluate the contents of $c as perl code, and
prent the results:
print eval $c;

Putting it together:
#!/usr/bin/perl
use strict;
use warnings;

my $a = '123';
my $b = '456';
my $c = '"$a $b"';

print "C: ", eval $c, "\n";

$a = 'abc';
$b = 'def';
print "C: ", eval $c, "\n";
__END__

C: 123 456
C: abc def

Paul Lalli
 
B

Brian McCauley

Paul said:
You have asked a Self Answering Question

perldoc -f eval

However you may want to consider avoiding eval.

See FAQ: "How can I expand variables in text strings?"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top