Mike Lesser wrote:
Hiya. I'm looking for the correct Perl style for testing and storing a return value in a control statement. The solution in any other language is pretty obvious, but I get the distinct impression that there's a 'right' way in Perl...

Let's say I want to test a scalar returned from a subroutine, and also keep a copy for my own use:

 $scalar = sub( $argument );

 if( $scalar ){
 }

Naturally that's no big deal. Now let's say I have a tree I want to traverse, or some similar open-ended thing to evaluate, and want to run it until a condition is reached..

 while( read_tree( $argument ){
 }

Again no biggie. The problem is if I want to keep the result. Obviously I can't do this:

while( $tree_element = read_tree( $argument ) ){
   do_something( $tree_element );
}

I can come up with a brute-force solution of course, but there's probably a better, Perlish way that I'm not aware of. In addition, I don't expect a return value from some module to be consistently undefined or zero; it could change under some circumstances. This makes me think that the problem has been dealt with long ago, and just doesn't stick out in the llama/alpaca/whatever books.

Hopefully I explained this correctly!

while (my $x = func()) {
 :
}

is perfectly valid. In Perl every operator returns a value, and the assignment
operator is no exception. It's value is the expression on the left of the equals
sign, and it's even an lvalue so you can do things like

 ($x = 3)++;

leaving $x with a value of four. This sort of thing is more useful for things 
like

 $p = $q = 'A';

which is the same as

 $p = ($q = 'A');

or

 $q = 'A'; $p = $q;

But the bottom line is that your while loop is quite valid.

HTH,

Rob


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to