Reputation: 115
I want to substitute value of variable 'c' and 'd' to variable 'a' and 'b' respectively in the example below, and this process should go on for 'n' times.
#!/usr/bin/perl
my $a = 4;
my $b = 6;
my $c = $a + $b;
my $d = $a * $b;
print "$c\n";
print "$d\n";
$a = $c;
$b = $d;
i.e. for each iteration of a loop the calculated value of 'c' and 'd' should be the new value of 'a' and 'b' respectively for 'n' times so that new values of 'c' and 'd' will be generated. I am not able to substitute the values. How can I set the condition to a loop for 'n' times? The desired output should be in the form:
c= val1 val2 val3......valn
d= val1 val2 val3......valn.
Upvotes: 0
Views: 132
Reputation: 35198
#!/usr/bin/perl
use strict;
use warnings;
use bigint;
my ( $sum, $times ) = ( 4, 6 );
my $count = 8;
my @sum;
my @times;
for ( 1 .. $count ) {
( $sum, $times ) = ( $sum + $times, $sum * $times );
push @sum, $sum;
push @times, $times;
}
print "c = @sum\n";
print "d = @times\n";
Outputs:
c = 10 34 274 8434 2244274 18859318834 42320461010388274 798134711765191824044221234
d = 24 240 8160 2235840 18857074560 42320442151069440 798134711722871363033832960 33777428948505262401578369250143488058711040
Upvotes: 1
Reputation: 3380
This should work:
#!/usr/bin/env perl
## Don't use $a and $b, they are special variables
## used in sort().
my $foo=4;
my $bar=6;
## The number of iterations
my $n=5;
## These arrays will hold the generated values
my (@sums, @products);
## Use a for loop
for (1 .. $n) {
my $sum=$foo+$bar;
my $product=$foo*$bar;
## save the results in an array to print later
push @sums, $sum;
push @products, $product;
$foo=$sum;
$bar=$product;
}
print "Sum=@sums\nProduct=@products\n";
Upvotes: 0
Reputation: 126722
The $a
and $b
variables are reserved for use by the sort
operator.
This will do what you want
use strict;
use warnings;
my ($aa, $bb) = (4, 6);
my $n = 5;
for (1 .. $n) {
my ($cc, $dd) = ($aa + $bb, $aa * $bb);
print "$cc\n", "$dd\n\n";
($aa, $bb) = ($cc, $dd);
}
output
10
24
34
240
274
8160
8434
2235840
2244274
18857074560
Upvotes: 1