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?
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.
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.
split() will return an array.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With