Perl: Loop Thru List

By Xah Lee. Date: . Last updated: .

In Perl, looping thru a list is typically done with “for”:

# -*- coding: utf-8 -*-
# perl

@myList = ('one', 'two', 'three', 'infinity');
for $xx (@myList) {
    print $xx, "\n";            # print each element
}

To loop thru a list using indexs, do like this:

# -*- coding: utf-8 -*-
# perl

@myList = ('one', 'two', 'three', 'infinity');
for ($i=0; $i < scalar(@myList); $i++) {
    print "$i $myList[$i], ";
} # prints: 0 one, 1 two, 2 three, 3 infinity,

A typical way to loop thru a hash is:

# -*- coding: utf-8 -*-
# perl

%myHash = ('john',3, 'mary',4, 'jane',5, 'vicky',7);
for $key (keys %myHash) {
    print "Key and Value pair is: $key, $myHash{$key} \n";
}

perldoc perldsc