July 2013 Archives

function return in scalar context

sub lowercase {
    return map { lc } @_ ;
}

$jim = lowercase('jim') ;
print "$jim\n" ;

Naturally that this snippet of code prints 1. I understand the explanation of "an array in scalar context blah blah blah". But it's so counter-intuitive because many functions are intended to mutate each element in a list. Presumably one should define separate functions depending on whether an array is expected, but that's so non-perlish. There's no elegant way to throw the wantarray operator in that example function. And even if there was, it's awkward to use the same idiom repeatedly.

I'd prefer simply to use a pragma such as the following:

use Function::ReturnScalar qw( first ) ;

## use Function::ReturnScalar qw( last ) ;      # optional alternative

## use Function::ReturnScalar qw( count ) ;   # optional alternative

sub lowercase {
    return map { lc } @_ ;
    }

$jim = lowercase('Jim') ;                                  # $jim == 'jim'

The pragmas in the above example don't exist. At least, even after posting on perlmonks, I can't find anything equivalent. But in a couple of hours, I wrote a rudimentary module that performs this function.

About Jim Schueler

user-pic NoSQL::PL2SQL is everything I've got.