RedGrittyBrick
RedGrittyBrick

Reputation: 4002

Perl compound condition for while?

I have something like

my $ token = readToken();
while (length($token) > 0) {
  # do stuff with $token
  $token = readToken();
}

I can't help feeling I have missed a construction where I don't have two calls to readtoken

Upvotes: 0

Views: 61

Answers (4)

shawnhcorey
shawnhcorey

Reputation: 3601

Your original loop should be:

my $token = readToken();
while (length($token) > 0) {
  # do stuff with $token
}continue{
  $token = readToken();
}

The difference is that anything in the continue clause will be executed when next is called. To skip the continue but loop again, use redo.

See:

Upvotes: -1

Borodin
Borodin

Reputation: 126722

Your own answer is pretty good. Or you can write an infinite loop and construct the while logic by hand:

while () {
  my $token = readToken();
  last if length($token) == 0;
  # do stuff with $token
}

Upvotes: 3

Jens
Jens

Reputation: 69440

Try this:

my $token; 
while (($token = readToken()) && (length($token) > 0)) {
  # do stuff with $token
}

Upvotes: 1

RedGrittyBrick
RedGrittyBrick

Reputation: 4002

This seems to work

while ( length( my $token = readToken() ) > 0 ) {
  # do stuff with token
}

Upvotes: 3

Related Questions