微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/Perl/172975.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐