perllexical-scope

Perl replace value without updating array


I have the following Perl script.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my @fruits = qw(apple banana orange pear);

print Dumper \@fruits;

foreach my $fruit (@fruits) {
  $fruit =~ s|apple|peach|;
}

print Dumper \@fruits;

The following is returned.

$VAR1 = [
          'apple',
          'banana',
          'orange',
          'pear'
        ];
$VAR1 = [
          'peach',
          'banana',
          'orange',
          'pear'
        ];

I do not understand why the following line has changed apple to peach in the @fruits array, as I thought this line would only apply to the $fruit variable, not the @fruits array.

$fruit =~ s|apple|peach|;

Solution

  • In the html doc of perl we have the following statement for foreach loops:

    the foreach loop index variable is an implicit alias for each item in the list that you're looping over

    This means, you do not get a copy of each array element. The variable $fruit is only a reference to an array element. Its value can be modified if the array element can be modified. The modification applies to the original array element.