开发者

Perl anonymous list question

Why this doesnt wo开发者_StackOverflow社区rk?

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.

Thanks,


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;

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

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


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 =~ /^([^,]*)/;


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜