1

this program should execute three times but is executing only twice. Can anyone explain how this foreach loop will work in perl.

#!/usr/bin/perl
use strict;
use warnings;
my @arr=("sandeepr", "vijay","vikas");
for my $i( @arr)
{
    print @arr;
    my $b=pop(@arr);
    print "\n $b";
}
3
  • 4
    You are iterating over an array, so you should just print $i; You are also modifying the array you are iterating over, which is generally a bad idea and can cause unexpected results. Better to copy the array that you wish to manipulate. Commented Mar 18, 2018 at 4:41
  • 1
    Also, 1-letter variables are in general not a good idea, but specifically in perl, the variables $a and $b have a special purpose, see perldoc -f sort Commented Mar 18, 2018 at 4:42
  • if you want to print the array 3 times, you can: for (1..3) { print @arr; } Commented Mar 18, 2018 at 4:46

1 Answer 1

11

perlsyn:

If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.

As confused as this makes Perl, you appear to be even more confused. What are trying to do? Print the elements in reverse order? If so, you could use

for my $ele (reverse @arr) {
   print("$ele\n");
}

or

for my $i (1..@arr) {
   my $ele = $arr[-$i];
   print("$ele\n");
}

or

while (@arr) {
   my $ele = pop(@arr);
   print("$ele\n");
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks ikegami for replying. yeah you are correct i am trying to print array in reverse order ( without using inbuilt reverse function though)
@rawatsandeep1989 what is the purpose of NOT using built-ins for your need? Just to learn how it works or something else?
@patrick Mevzek ,yes just to learn how it works. :-) what if there were no builtins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.