Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `$v = () = split` return 1?

Tags:

perl

perldoc says "a list assignment in scalar context returns the number of elements on the right-hand side of the list assignment" but when I try this code:

perl -e '$_="aaaaa";print $v=(()=split //)'

The output is 1 which makes me confused. (The answer I expect is 5.)

Can anybody explain this?

like image 737
hexsum Avatar asked Aug 28 '12 09:08

hexsum


People also ask

What does split () return in Python?

The string manipulation function in Python used to break down a bigger string into several smaller strings is called the split() function in Python. The split() function returns the strings as a list.

What does the split method return?

The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What does split () return if the string has no match in Java?

split() will return an array.

Does the split method return a list?

The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.


2 Answers

According to split documentation:

When assigning to a list, if LIMIT is omitted, or zero, Perl supplies a LIMIT one larger than the number of variables in the list <...>

Since you specify empty list, split only returns 1 result and this number of results is exactly what ends in your variable.

like image 80
Oleg V. Volkov Avatar answered Sep 19 '22 06:09

Oleg V. Volkov


split has some kind of crazy ultra-magic in it that allows it to know when it is on the right hand side of an assignment that has a list on the left hand side, and adjusts its behavior according to the number of items in that list.

This is described in perlfunc as being done "to avoid unnecessary work", but you've found an observable difference in behavior caused by that optimization.

To see some evidence of what happened, run your script through Deparse like this:

perl -MO=Deparse -e '$_="aaaaa";print $v=(()=split //)'

Update: I went looking for the code that implements this, and it's not where I expected it to be. Actually the optimization is performed by the assignment operator (op.c:Perl_newASSIGNOP) . split doesn't know that much about its context.

like image 42
Alan Curry Avatar answered Sep 23 '22 06:09

Alan Curry