in reply to Re: Counting matches.
in thread Counting matches.

If anyone is interested in more uses of list assignments in scalar context, consider functions that need to be able to return any scalar while also able to signal some special condition.

In C++, you might very well do something like

bool next(Type& arg) { if (...) { return false; } else { arg = ...; return true; } } while (i->next(arg)) { ... }

You could do the same in Perl

sub next { my $self = $_[0]; our $arg; local *arg = \$_[1]; if (...) { return 0; } else { $arg = ...; return 1; } } while ($i->next($arg)) { ... }

But another solution is to return either 1 scalar or 0 scalars.

sub next { my ($self) = @_; if (...) { return; } else { return ...; } } while (my ($arg) = $i->next()) { ... }

One might be tempted to do the following, but it won't work if the function can return a false value (such as 0, "0", "", undef, etc).

while (my $arg = $i->next()) { ... }