Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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|;
like image 587
JeremyCanfield Avatar asked Apr 06 '26 20:04

JeremyCanfield


1 Answers

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.

like image 106
Donat Avatar answered Apr 10 '26 00:04

Donat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!