Perl: Looping through an array

Articles may may have files attached at the end of the post

How to go through each elements of an array.

  1. #!/usr/bin/env perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. my @myarray = ('element1', 'element2', 'element3');
  7. print "Using the default implied scaler (\$_)\n";
  8.  
  9. foreach (@myarray) {
  10.   print "\t".$_."\n";
  11. }
  12.  
  13. print "\nUsing a variable\n";
  14. foreach my $elmt (@myarray) {
  15.   print "\t".$elmt."\n";
  16. }

will output

$ perl array.pl
Using the default implied scaler ($_)
        element1
        element2
        element3

Using a variable
        element1
        element2
        element3