kgherman has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, I'm trying to write a while loop and I'm running into some problems with the condition that I need to put in the loop. I would like to know if I can put as a condition a user defined function that has an outcome of TRUE or FALSE.

I'm not very familiar with how to write such type of functions so before I venture into this I would like to know whether it's doable to begin with.

Replies are listed 'Best First'.
Re: User defined function in while loop
by toolic (Bishop) on Jun 19, 2015 at 18:43 UTC
    Yes. This considers 1 as TRUE and 0 as FALSE:
    use warnings; use strict; my $i = 0; while (foo($i)) { print "i = $i\n"; $i++; } sub foo { my $x = shift; return ($x < 5) ? 1 : 0; } __END__ i = 0 i = 1 i = 2 i = 3 i = 4
Re: User defined function in while loop
by ikegami (Patriarch) on Jun 19, 2015 at 18:41 UTC
    Yes, you must provide an expression that returns a true or false value, and sub calls are expressions.
    while (more(...)) { ... }
    while (!done(...)) { ... }
    while (my $item = get(...)) { ... }
Re: User defined function in while loop
by Laurent_R (Canon) on Jun 19, 2015 at 20:15 UTC
    Sure you can. As exemplified in this simple command-line (one-liner) script;
    $ perl -E 'my $count = 5; say $count while decr($count); sub decr {-- +$_[0];}' 4 3 2 1
    Note that, in this case, $_[0] is an alias for $count, so that decrementing $_[0] does decrement $count. Not necessarily a best practice in general, but OK IMHO for a one-liner.

    Or a variation of the same not using aliases:

    $ perl -E 'my $count = 5; say $count while $count = decr($count); sub + decr {return -1 + shift;}' 4 3 2 1