perl – 是否有一个单行来获得分割的第一个元素?

前端之家收集整理的这篇文章主要介绍了perl – 是否有一个单行来获得分割的第一个元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
而不是写:
@holder = split /\./,"hello.world"; 
print @holder[0];

是否有可能只做一个单行,只是得到分裂的第一个元素?就像是:

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

当我尝试第二个例子时,我收到以下错误

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

解决方法

你应该尝试你的预感。这是怎么做到的。
my $first = (split /\./,"hello.world")[0];

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

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

要打印,请使用

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

要么

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

加号是因为句法歧义。它表示以下所有内容都是要打印的参数。 perlfunc documentation on 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).

在上述情况下,我发现这种情况更容易编写和阅读。因人而异。

原文链接:https://www.f2er.com/Perl/172975.html

猜你在找的Perl相关文章