Forcing a list context in Perl

You’re confused because you think = is a single operator while it can result in two different operators: a list assignment operator or a scalar assignment operator. Mini-Tutorial: Scalar vs List Assignment Operator explains the differences.

my $b = (33,22,11);
------------------            Scalar assign in void context.
        ----------            List literal in scalar context. Returns last.

my @b = (33,22,11);
------------------            List assign in void context.
        ----------            List literal in list context. Returns all.

my $b = ( () = (33,22,11) );
---------------------------   Scalar assign in void context.
        -------------------   List assign in scalar context. Returns count of RHS
               ----------     List literal in list context. Returns all.

my @b = ( () = (33,22,11) );
---------------------------   List assign in void context.
        -------------------   List assign in list context. Returns LHS.
               ----------     List literal in list context. Returns all.

As for your title, forcing list context is impossible per se. If a function returns a list when a scalar is expected, it results in extra values on the stack, which leads to operators getting the wrong arguments.

You can, however, do something like:

( EXPR )[0]

or

( EXPR )[-1]

EXPR will be called in list context, but the whole will return just one element of the returned list.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)