in reply to python-like split+array access -- possible?

If you used the warnings pragma, perl would have told you what is wrong:

C:\>perl -we "print ( split '_' , $myString )[1]" print (...) interpreted as function at -e line 1. syntax error at -e line 1, near ")[" Execution of -e aborted due to compilation errors.

The following works:

C:\>perl -we "$myString = '123_456'; print( ( split '_' , $myString )[ +1] )" 456

The difference is that print is not a keyword in Perl but a function with optional parentheses, unlike in Python where it is a keyword which doesn't need parentheses.

As an aside, you shouldn't use strings as the first argument to split but regular expressions, as split will interpret the string as a regular expression as well, but passing a regular expression makes it more explicit what happens:

C:\>perl -we "$myString = '123_456'; print( ( split /_/ , $myString )[ +1] )" 456

Replies are listed 'Best First'.
Re^2: python-like split+array access -- possible?
by Juerd (Abbot) on Oct 26, 2005 at 19:56 UTC