Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multi-line equations...conditional

Status
Not open for further replies.

CJason

Programmer
Oct 13, 2004
223
US
I am needing to to SIMILAR to this pseudo-psuedo-code:

$a = $b
foreach $c (@d) {
+ $c
}
+ $e;

I'm trying to think of the best way of doing. Can I somehow concatenate a string to make the full equation...then maybe do an eval or something???

Thanks in advance!
 
Like this?

my $cmd = '$a + $b';
my ($a, $b, $e) = (10,20,30);

foreach $c (2,3,4,5) {
$cmd .= " + $c";
}
$cmd .= ' + $e';
print $cmd."\n";
print eval($cmd);

\0
 
Unless you are specifically trying to write a command-line calculator, you are better off not using eval
Code:
use strict;
use warnings;

my $a;
my $b = 1;
my @d = (2, 3, 4, 5);
my $e = 6;

foreach ($b, @d, $e) {
   $a += $_
}

print $a;

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
That's a pretty cool technique, stevexff!!! However, my problem is actually a little more complicated than my example here. I just wrote it this way to simplify things. I'm afraid eval is my only option.
 
You also really should avoid using $a and $b as packaged variables as they are used by perl internally for sorting.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top