in reply to Array element getting deleted
Consider the behavior when $_ is not protected from the side-effects of the while loop:
Consider the behavior with explicit localization:>perl -wMstrict -MData::Dumper -le "my @array = qw(A B C); $_ = 'foo'; print qq{before foreach loop:}; print Dumper $_, \@array; foreach (@array) { print qq{in foreach loop before while loop: \$_ is $_}; while (<DATA>) { print; } print qq{in foreach loop after while loop: \$_ is }, defined() ? $_ : 'UNdefined' ; } print qq{after foreach loop:}; print Dumper $_, \@array; __DATA__ " before foreach loop: $VAR1 = 'foo'; $VAR2 = [ 'A', 'B', 'C' ]; in foreach loop before while loop: $_ is A in foreach loop after while loop: $_ is UNdefined in foreach loop before while loop: $_ is B in foreach loop after while loop: $_ is UNdefined in foreach loop before while loop: $_ is C in foreach loop after while loop: $_ is UNdefined after foreach loop: $VAR1 = 'foo'; $VAR2 = [ undef, undef, undef ];
All the usual suspects: Foreach Loops in perlsyn, $_ (or $ARG if you use English;) in perlvar, map, grep.>perl -wMstrict -MData::Dumper -le "my @array = qw(A B C); $_ = 'foo'; print qq{before foreach loop:}; print Dumper $_, \@array; foreach (@array) { print qq{in foreach loop before while loop: \$_ is $_}; { local $_; while (<DATA>) { print; } } print qq{in foreach loop after while loop: \$_ is }, defined() ? $_ : 'UNdefined' ; } print qq{after foreach loop:}; print Dumper $_, \@array; __DATA__ " before foreach loop: $VAR1 = 'foo'; $VAR2 = [ 'A', 'B', 'C' ]; in foreach loop before while loop: $_ is A in foreach loop after while loop: $_ is A in foreach loop before while loop: $_ is B in foreach loop after while loop: $_ is B in foreach loop before while loop: $_ is C in foreach loop after while loop: $_ is C after foreach loop: $VAR1 = 'foo'; $VAR2 = [ 'A', 'B', 'C' ];
|
|---|