in reply to Re^2: Perl for loop
in thread Perl for loop
Here's an approach to what my guess is about the gist of the EDIT section of your OP. I don't understand why you would want to do something this way; please see other posts in this thread for what I would consider to be better approaches (but again, I don't really understand what you want to do). However, this reply is in direct response to your edited OP.
Note the ${ $student[$i] } syntax needed to access an array element that is a scalar reference. This code runs under Perl version 5.8.9+. What version of Perl are you using?c:\@Work\Perl\monks>perl -wMstrict -le "use Data::Dump qw(dd); ;; my ($name1, $name3, $name5, $name7, $name9, $name11) = qw(Bill Jill Phil Will Gill Al); my @student = (\$name1, \$name3, \$name5, \$name7, \$name9, \$name11) +; ;; my ($age1, $age2, $age3, $age4, $age5, $age6) = (11, 22, 33, 44, 55, 66); my @all = (\$age1, \$age2, \$age3, \$age4, \$age5, \$age6); ;; dd \@student; dd \@all; ;; for (my $i = 0; $i < @student; ++$i) { if (${ $student[$i] } eq 'Al') { ${ $all[$i] } = ${ $all[$i] } * 11; } elsif (${ $student[$i] } eq 'Phil') { ${ $all[$i] } = ${ $all[$i] } * 111; } else { print qq{no satisfying condition for index $i}; } } ;; dd \@all; " [\"Bill", \"Jill", \"Phil", \"Will", \"Gill", \"Al"] [\11, \22, \33, \44, \55, \66] no satisfying condition for index 0 no satisfying condition for index 1 no satisfying condition for index 3 no satisfying condition for index 4 [\11, \22, \3663, \44, \55, \726]
Note also that a syntactic shortcut for a statement like
my @all = (\$age1, \$age2, \$age3, \$age4, \$age5, \$age6);
is
my @all = \($age1, $age2, $age3, $age4, $age5, $age6);
Update: Note also that a more Perlish, less error-prone syntax for the for-loop would be
for my $i (0 .. $#student) { if (${ $student[$i] } eq 'Al') { ... } ... }
Give a man a fish: <%-{-{-{-<
|
---|