in reply to Perl for loop

Hi MissPerl,

Your question is not very clear, but let's say that you mean you want to loop through two lists of things at the same time. You could store the things in two arrays and use the same index on each array as you go through the loop. That seems to be what you were trying to do.

my @names = ('Fred', 'Wilma', 'Barney', 'Betty'); my @ages = ( 40, 38, 42, 41 ); for my $i ( 0 .. 3 ) { print "$names[ $i ] is $ages[ $i ]\n"; }
... but you'd be better off storing your data in a hash, then you don't have to worry about keeping the index the same, or if the lists get out of order:
my %flintstones = ( Fred => 40, Wilma => 38, Barney => 42, Betty => 41, ); for my $name ( keys %flintstones ) { print "$name is $flintstones{ $name }\n"; }

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Perl for loop
by MissPerl (Sexton) on Jun 02, 2017 at 07:15 UTC
    Apologize for not being clear. I've just edited my question, do you think there is a way to work out for this?

      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.

      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 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?

      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:  <%-{-{-{-<