How do i use the foreach control structure in perl?



  • foreach allows you to process the entire array in perl.

    See perlsyn man page: perlsyn(1) - Perl syntax

    Takes the animal array and processes each element, printing a line for each animal.

    @animals = ("lion", "tiger", "bear", "monkey");
    foreach $animal (@animals) {
    	$n += 1;
    	print "Hello, my name is $animal and I'm an animal, in the 100m sprint my number is $n\n";
    }
    

    Result is:
    Hello, my name is lion and I'm an animal, in the 100m sprint my number is 1
    Hello, my name is tiger and I'm an animal, in the 100m sprint my number is 2
    Hello, my name is bear and I'm an animal, in the 100m sprint my number is 3
    Hello, my name is monkey and I'm an animal, in the 100m sprint my number is 4


Log in to reply
 

© Lightnetics 2024