develooper Front page | perl.perl5.porters | Postings from December 2011

[perl #103212] Split to list assignment in scalar context

Thread Next
James E Keenan via RT
December 5, 2011 18:08
[perl #103212] Split to list assignment in scalar context
Message ID:
On Tue Nov 08 14:37:05 2011, b_jonas wrote:
> This is a bug report for perl from,
> generated with the help of perlbug 1.39 running under perl 5.14.2.
> -----------------------------------------------------------------
> [Please describe your issue here]
> This command gives an unexpected result:
> $ perl -wE 'say scalar(($_x, $_y) = split "/",
> "one/two/three/four/five");'
> 3
> One would naively think it should return 5, just like this command:
> $ perl -wE 'say scalar((@_x) = split "/", "one/two/three/four/five");'
> 5

But we also need to take into account the documentation for the 'scalar'
function (perldoc -f scalar):

Because "scalar" is a unary operator, if you accidentally use a
parenthesized list for the EXPR, this behaves as a scalar comma
expression, evaluating all but the last element in void context
and returning the final element evaluated in scalar context.
This is seldom what you want.

My hunch is that in your first case above, the "final element evaluated
in scalar context" would be '3', the number of elements in ( qw| three
four five | ).

Thank you very much.
Jim Keenan

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About