Perl: Please explain the following while () behavior to me.

1. What does while (<$filehandle>)iteration through the file without visible problems, but it does not iterate over lists or arrays without manipulating the array itself (for example, using while ($_ = shift @array){print $_}). How does this happen?

2. When is it while ($var = @array){print $var}possible to iterate over the entire array? Should it $varjust get the number of indices in @arrayand return that value (to create an infinite loop)?

From my understanding, while()the condition of the operator and the cycles is read until it finds it true. What I find confused is its behavior around file descriptors, lists, etc.

Please help me understand more about while(), as I find this statement to be very confusing sometimes.

+3
source share
2 answers

Let's start by viewing while(<$filehandle>). This is actually a Perl abbreviation:

while (defined($_ = <$filehandle>)) {
    print $_;
}

So, each time through the loop, you read the next line from the file, and if it is not defined, you will exit the loop. If defined, you continue. As you would expect, it whilewill loop until the condition is true.

You can see it by running perl -MO=Deparse program.pl. You can also check the documentation in Loop Control . The diamond operator is the same as the readline subroutine (it reads the next line from the file).


while ($_ = shift @array){print $_} , while. shift . , $_ , .


while ($var = @array){print $var}, $var . , @array . true, perlsyn

0, '0' "", () undef . .

, :

perl -le 'my @array = qw(a b c d e); my $var = @array; print $var'

5, 5 . while , 0 , , 1 .

:

### This code will print 5 forever ###
my @array = qw(hi this is a test);
my $var;
while ( $var =  @array ) {
    print "$var\n";
}

2, , , .

+6

Perl, .

(< > ).

2, , IIRC.

0

All Articles