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

I'm wondering if there is an easy way to impose scalar context on a return value (wantarray). It's easy to do it the other way round - force list context. This can be done with (function(...)).

The situation I have is with Class::DBI searches, which return an iterator in scalar context and return the list of all matching objects in list context. I want to make an array of iterators, viz:

my @iters = (My::Table1->search(age => 18), My::Table2->search(name => + 'Smith));

This does the slurp, and does not give me the iterators that I want. I have a workaround, by way of using dummy scalar variables, but I think it is ugly, but works as intended:

my @iters = ((my $tab1 = My::Table1->search(age => 18)), (my $tab2=My: +:Table2->search(name => 'Smith)))

Is there some idiomatic, neat way that I have missed?

Update: scalar - doh! Interesting, most of the time I use scalar to count things. I forgot that it was originally designed for another purpose.

--

Oh Lord, won’t you burn me a Knoppix CD ?
My friends all rate Windows, I must disagree.
Your powers of persuasion will set them all free,
So oh Lord, won’t you burn me a Knoppix CD ?
(Missquoting Janis Joplin)

Replies are listed 'Best First'.
Re: Forcing scalar context
by blazar (Canon) on Aug 03, 2005 at 10:05 UTC
    scalar! Notice that there's not a corresponding function for list context for there are easier ways to impose it, as you notice yourself.
Re: Forcing scalar context
by gellyfish (Monsignor) on Aug 03, 2005 at 10:08 UTC

    You probably want to try:

    my @iters = (scalar My::Table1->search(age => 18), scalar My::Table2-> +search(name => 'Smith));

    /J\

Re: Forcing scalar context
by blazar (Canon) on Aug 03, 2005 at 10:44 UTC
    Update: scalar - doh! Interesting, most of the time I use scalar to count things. I forgot that it was originally designed for another purpose.
    Interesting also because IMHO it is rarely needed to count things, e.g. I see people doing all the time things like:
    complain if scalar @stuff < 2;
    whereas
    complain if @stuff < 2;
    is just as fine!
Re: Forcing scalar context
by Anonymous Monk on Aug 03, 2005 at 12:16 UTC
    It's easy to do it the other way round - force list context. This can be done with (function(...)).
    Putting parenthesis around an expression does NOT create list context:
    sub context {wantarray ? "LIST" : "SCALAR"} my $context = (context); print $context, "\n"; __END__ SCALAR
    Perhaps you are confused with:
    sub context {wantarray ? "LIST" : "SCALAR"} my($context) = context; print $context, "\n"; __END__ LIST