Your confusion lies in the substitution happening in these two for loops

#Loop 1
foreach my $l (@ar) {
        $l =~ s/Fred/Thomas/;
}

In this loop you are assigning a local (my) variable $l to each element of
@ar and substituting on that local which immediately goes out of scope.

#Loop 2
for( my $x=0;$x<@ar;$x++) {
        my $l = $ar[$x];
        $l =~ s/Fred/Thomas/;
}

In this loop you are assigning a local (my) variable $l to a reference of
each element of @ar and substituting on that local which immediately goes
out of scope, BUT the reference is still pointing to the @ar element which
does NOT go out of scope, thus retatining the value.

Here's another loop that acts like Loop#2 but feels like Loop #1
# My loop
foreach (@ar) {
        s/Fred/Thomas/;
}

>From 


-----Original Message-----
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf Of Andreas
Karl Wittwer
Sent: Saturday, May 08, 2004 11:33 AM
To: ActiveState
Subject: Array behavior: please expalin ...


Hi,

I thought I know a bit of perl but this is confusing ...

=== cut 1 ===
#! /usr/bin/perl
use strict;
my @ar = ();
push @ar,"Harry Fred Paul";
push @ar,"Fred Ringo John";
push @ar,"Georg Don Fred";

foreach my $l (@ar) {
        $l =~ s/Fred/Thomas/;
}
t();
sub t {
        for(my $z=0;$z<@ar;$z++) {
                my $l = $ar[$z];
                if($l =~ /Fred/) {
                print "Fred joined\n";
                } else {
                print  "fred missed\n" ;
                }
        }

}


fred missed
fred missed
fred missed

=== end cut 1 ===


=== cut 2  ===

#! /usr/bin/perl
use strict;
my @ar = ();
push @ar,"Harry Fred Paul";
push @ar,"Fred Ringo John";
push @ar,"Georg Don Fred";

for( my $x=0;$x<@ar;$x++) {
        my $l = $ar[$x];
        $l =~ s/Fred/Thomas/;
}
t();
sub t {

        for(my $z=0;$z<@ar;$z++) {
                my $l = $ar[$z];
                if($l =~ /Fred/) {
                print "Fred joined\n";
                } else {
                print  "fred missed\n" ;
                }
        }
}


Fred joined
Fred joined
Fred joined

=== end cut 2 ===

Someone able to explain. please?

Best regards,

Andreas Karl Wittwer
Phone: +49-7052-92206
FAX:   +49-7052-92208
Mobil: +49-172-542 541 4



_______________________________________________
ActivePerl mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
_______________________________________________
ActivePerl mailing list
[EMAIL PROTECTED]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to