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

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758207384, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Perl/functions/foreach(99): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78