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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding a variable onto a variable

Status
Not open for further replies.

smm4301

Programmer
Aug 1, 2003
5
US
I have variables named, for simplicity, $x1, $x2, $x3, up to $x20 and each one does the exact same thing.

Is there any way to have a loop that has $x$i for $i from 1 to 20?

A foreach loop will not work, at least I don't think it will, because I also have variables $x_font1 to $x_font20 to change the font of the $x's depending on valid input which put me right back where I started.

Thanks.
 
Code:
$foo = 1;
$bar = 2;
$foo += $bar
print $foo;
This would print '3' to the screen.

If you want to do this 20 times, you could do a regular
Code:
for
loop.

--
Andy
 
The variables are not integers.
Is there a way if I have a variable $x6 which holds a string, to have that string print out for $x$i where $i = 6?
 
Is this what you need?

for ($i=1; $i<21; $i++) {

$x{$i} = $i;

print &quot;\$x{$i} = $x{$i}&quot;;

}
 
perldoc -f join
Code:
       join EXPR,LIST
               Joins the separate strings of LIST into a single string with
               fields separated by the value of EXPR, and returns that new
               string.  Example:

                   $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);

               Beware that unlike &quot;split&quot;, &quot;join&quot; doesn't take a pattern as
               its first argument.  Compare the split entry elsewhere in this
               document.

--
Andy
 
You would need to use symbolic references to accomplish what I think you are tring to do. Assuming your 20 variables: $x1, $x2, $x3 ... $x20 you could print the contents of each with the following loop:
Code:
for (1..20) {
 # uncomment next line if using strict
 # no strict &quot;refs&quot;;
 print ${ 'x' . $_ };
}
This will not work if you use strict unless you uncomment the 'no strict &quot;refs&quot;;' pragma. You are better of making x an array or a hash. Then you don't have to worry about symbolic refs.

Hope that helps.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top