At 10:59 AM 4/17/2001, you wrote:
>i have this program:
>
>$sup1='a';
>$sup2='b';
>$sup3='c';
>
>for ($i=1 ; $i<4 ;$i++){
>     print $sup($i);
>}
>
>but give error, why???

First off, you need to make an array.  All you have are some scalars with 
similar names.  You could use symbolic references to print all of the 
variables, but that's not very "beginner-like", not to mention total 
overkill for the situation.  You could initialize the array like:

$sup[0] = 'a';
$sup[1] = 'b';
$sup[2] = 'c';

and your print statement should read:

print $sup[$i];

Notice the hard brackets as opposed to parenthesis.  But this isn't very 
Perlish at all.  You can clean up the initialization of your array, using a 
list context assignment.  I'll just write out a few different ways you 
could do it.  (Remember, TIMTOWDI - There's More Than One Way to Do It)

use strict;
my @sup = ( 'a', 'b', 'c' );

for (0..2){
     print $sup($i);
}

or do the loop like this:

foreach (@sup) {
     print;
}

In the example above, each element of the array will get assigned to $_ as 
the foreach loops over it.  Then print, conveniently, when not supplied 
with any arguments will print the contents of $_.  You could say:

     print $_;

but saying just 'print;' is the same.

Hope this helps.

Sean O'Leary

BTW - If anyone wants to see the symbolic reference code, here it be (or 
one version of it anyway)

use strict;

our $sup1 = 'a';
our $sup2 = 'b';
our $sup3 = 'c';

{
     no strict 'refs';
     for (1..3){
         print ${ "sup$_" };
     }
}

Be sure to be using a nice, new Perl, though.  5.6.0+.

Later,

Sean.

Reply via email to