glendeni has asked for the wisdom of the Perl Monks concerning the following question:

Have used perl for 25 years, but after a day of contemplation still cannot figure out why use of tr changes two variables instead of one, i.e. why $char1 is being upper-cased in following
my @chars = ( 'a', 'b' ) ; foreach my $char1 ( @chars ) { foreach my $char2 ( @chars ) { print "BEFORE: $char1 $char2 \n" ; $char2 =~ tr/a-z/A-Z/ ; # $char1 ALSO UPPER-CASED !? print " AFTER: $char1 $char2 \n" ; } }
with output
BEFORE: a a AFTER: A A BEFORE: A b AFTER: A B BEFORE: B A AFTER: B A BEFORE: B B AFTER: B B

Replies are listed 'Best First'.
Re: Two variables changed by tr
by hippo (Archbishop) on Jul 03, 2024 at 18:36 UTC

    foreach aliases into the list rather than copying. As you have 2 nested loops over the same array, half the time your two lexicals are aliases for the same item in the array.


    🦛

      Thanks - learned something new today
        Compare:
        use warnings; use strict; my @chars = ( 'a', 'b' ) ; foreach my $char1 ( @chars ) { foreach my $char2 ( @chars ) { print "BEFORE: $chars[0] $chars[1] \n" ; $char2 =~ tr/a-z/A-Z/ ; # $char1 ALSO UPPER-CASED !? print " AFTER: $chars[0] $chars[1] \n" ; } }

      Example:

      my @chars = qw( a b c ); for my $char ( @chars ) { $char = uc( $char ); } say "@chars"; # A B C