是否有一个单行来获取拆分的第一个元素? [英] Is there a one-liner to get the first element of a split?

查看:41
本文介绍了是否有一个单行来获取拆分的第一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而不是写:

@holder = split /\./,"hello.world"; 
print @holder[0];

是否可以只做一个单行来获取拆分的第一个元素?类似的东西:

is it possible to just do a one-liner to just get the first element of the split? Something like:

print (split /\./,"hello.world")[0]

当我尝试第二个示例时出现以下错误:

I get the following error when I try the second example:

print (...) interpreted as function at test.pl line 3.
syntax error at test.pl line 3, near ")["

推荐答案

您应该尝试过您的预感.就是这样做的.

You should have tried your hunch. That’s how to do it.

my $first = (split /\./, "hello.world")[0];

您可以使用仅获取第一个字段的列表上下文分配.

You could use a list-context assignment that grabs the first field only.

my($first) = split /\./, "hello.world";

要打印,请使用

print +(split /\./, "hello.world")[0], "\n";

print ((split(/\./, "hello.world"))[0], "\n");

存在加号是因为句法歧义.它表示接下来的所有内容都是 print 的参数.关于 print 的 perlfunc 文档进行了说明.

The plus sign is there because of a syntactic ambiguity. It signals that everything following are arguments to print. The perlfunc documentation on print explains.

注意不要在print关键字后跟一个左括号,除非你希望相应的右括号终止print的参数;在所有参数周围加上括号(或插入一个 +,但这看起来不太好).

Be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print; put parentheses around all arguments (or interpose a +, but that doesn't look as good).

在上面的例子中,我发现 + 更容易编写和阅读.天啊.

In the case above, I find the case with + much easier to write and read. YMMV.

这篇关于是否有一个单行来获取拆分的第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆