Take the 2-minute tour ×

Why this doesnt work?

my $str = 'we,you,them,us';

print $(split($str,','))[0];

I know I can do:

my @str = split...

but I remember there is a way to skip that.


share|improve this question
Heck, I can't even get it to compile. If $(...) could work for something, you might be getting something other than what you're expecting. But this is a case of the language just doesn't work that way. You might have gotten something out of the scalar dereferencing brackets ${...}. What's more it's looking in $_ for 'we,you,them,us' and not finding it. The thing you want to split is the second argument, the delimiter is the first. –  Axeman Nov 19 '10 at 21:56
add comment

3 Answers

up vote 8 down vote accepted

You have the order of arguments for split reverse. There should be no dollar sign in front of the parens. The following works (the plus sign forces perl to evaluate the following as expression):

use strict;
use warnings;


print +(split(',',$str))[0];
share|improve this answer
You have four characters in a row there, XYXY, where the first Y is doing something completely different from what the second Y is doing but which are identical in appearance. This is confusing. That’s why people switch to a fat comma in that scenario. Also, the leading plus to defeat argument saves you only one character at the cost of yet another possible source of confusion or error. I therefore advise rewriting that last line as print ( (split "," => $str)[0] ); instead. Isn’t that much more legible? I certainly think so, but your 1⅗·kilometrage may vary. –  tchrist Nov 19 '10 at 20:26
Thanks! and where can I read about this things? been looking in perltoc sub-man pages, but couldnt find any related stuff. –  snoofkin Nov 19 '10 at 21:02
@soulSurfer2010: Read about what? The best thing to do is chdir to the pod directory and grep liberally. –  tchrist Nov 19 '10 at 21:25
FWIW, @tchrist, your version would confuse me more. In mathematics the symbol => is the 'results in' operator. This makes the use of the fat comma in creating hashes make sense to me, key => (results in) value. While you are definitely correct that you could use this method to remove the XYXotherY problem, doesn't ( (split(/,/ , $a))[0] ) work too, now having XYX otherY (note space before otherY) –  Joel Berger Nov 20 '10 at 13:31
add comment

Any time you need to only access a small portion of a function's return value, you should check to see if there is a smaller scoped function you can use. In this case, I might use a regular expression:

print $str =~ /^([^,]*)/;
share|improve this answer
add comment

Using [split $str, ',']->[0]; would be fine.

share|improve this answer
no need to create an anonymous array –  Arkadiy Nov 19 '10 at 20:48
add comment

Your Answer


