Search notes:

Perl: foreach statement

Aliasing elements

When iterating over a list the iteration variable is aliased to the elements in the list. Thus, it's possible to change the values within the list in a foreach statement:
#!/usr/bin/perl
use warnings;
use strict;

my $g = 99;

foreach my $g (1..5) {
  p($g);
}
    
sub p {
  my $l = shift;
  printf ("%2d %2d\n", $g, $l);
}

# Output:
#
# 99  1
# 99  2
# 99  3
# 99  4
# 99  5
Github repository about-perl, path: /functions/foreach/localizing-variable.pl
Python doesn't seem to do that.

Localizing variable

The value of the variable in the foreach loop is only visible in the loop (and lost afterwards).
#!/usr/bin/perl
use warnings;
use strict;

my $g = 99;

foreach my $g (1..5) {
  p($g);
}
    
sub p {
  my $l = shift;
  printf ("%2d %2d\n", $g, $l);
}

# Output:
#
# 99  1
# 99  2
# 99  3
# 99  4
# 99  5
Github repository about-perl, path: /functions/foreach/localizing-variable.pl

See also

Perl functions

Index